babel / babel-loader

📦 Babel loader for webpack
MIT License
4.83k stars 451 forks source link

React - Module parse failed: You may need an appropriate loader to handle this file type. #173

Closed westdavidr closed 8 years ago

westdavidr commented 8 years ago

I've been banging my head against the wall all day trying to figure this one out.

ERROR in ./app/assets/frontend/main.jsx
Module parse failed: /Users/david/work/sd/sd-web/app/assets/frontend/main.jsx Line 4: Unexpected token <
You may need an appropriate loader to handle this file type.
|   render() {
|     return (
|       <h1>Hello, World</h1>
|     );
|   }

Here's my relevant package.json:

"devDependencies": {
  "babel-core": "^6.2.1",
  "babel-loader": "^6.2.0",
  "babel-preset-es2015": "^6.1.18",
  "babel-preset-react": "^6.1.18",
  "webpack": "^1.12.9"
}

and web pack.config.js:

module.exports = {
  entry: './app/assets/frontend/main.jsx',
  output: {
    path: __dirname + '/app/assets/javascripts',
    filename: 'bundle.js',
    resolve: {
      extensions: ['', '.js', '.jsx']
    },
    module: {
      loaders: [
        {
          test: /\.jsx?$/,
          loader: 'babel',
          exclude: /node_modules/,
          query: {
            cacheDirectory: true,
            presets: ['react', 'es2015']
          }
        }
      ]
    }
  }
}

and then running webpack from the command line.

Am I missing something obvious here?

westdavidr commented 8 years ago

I should add that if I run:

babel app/assets/frontend/main.jsx --presets es2015,react

from the command line, it parses correctly, which led me to believe it was an issue with babel-loader and/or webpack.

epicallan commented 8 years ago

i am having a similar issue with web pack and babel

stevenross commented 8 years ago

@westdavidr Your resolve and module properties are incorrectly enclosed in the output property. Try this:

module.exports = {
  entry: './app/assets/frontend/main.jsx',
  output: {
    path: __dirname + '/app/assets/javascripts',
    filename: 'bundle.js'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          cacheDirectory: true,
          presets: ['react', 'es2015']
        }
      }
    ]
  }
}
westdavidr commented 8 years ago

@stevenross You are correct. I'm not sure if I should bang my head harder for such a simple mistake, or thank you for the answer. Haha.

Thanks!

aseem2625 commented 8 years ago

This should help for those who're still looking for solution:

My webpack.config.js file with working hot reloading

require('webpack');

module.exports = {
    context: __dirname + '/src',
    entry: {
        javascript: "./app.js",
        html: "./index.html"
    },
    output: {
        filename: 'app.js',
        path: __dirname + '/dist'
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loaders: ['react-hot', 'babel-loader?presets[]=react,presets[]=es2015'],
                //loaders: ["react-hot", 'babel-loader'],
                //query: {
                //    presets : ['es2015', 'react']
                //}
            },
            {
                test: /\.html$/,
                loader: "file?name=[name].[ext]"
            }
        ]
    }
};
varunkot commented 8 years ago

Hi

I am start learning react and i am facing similar type of issue.

varunkot commented 8 years ago

web.config.js file

module.exports = { entry: [ './src/App.js' ], output: { path: __dirname, filename: 'app-min.js' }, resolve:{ extensions: ['','.js','.jsx'] }, module: { loader: [ { test: /.jsx?$/, loader: 'babel', exclude: /node_modules/, query: { presets: ['react','es2015'] } } ] } } App.js

import React from 'react'; class App extends React.Component { render(){ return (

Contact list

    )
}

}

error in console : app-min.js:47 Uncaught Error: Cannot find module "./src/App.js"

aseem2625 commented 8 years ago

Hey @varunkot To indent/organize your comment well for code snippets try putting your code inside

zeexan-dev commented 7 years ago

I am also facing same issue today.

webpack.config.js

module.exports = {
  entry: "./public/main.js",
  output: {
    path: __dirname + "/public",
    filename: "/bundle.js"
  },
  module: {
    loader: [{
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
          presets : ['es2015', 'react']
        }
    }]
  },
  watch: true
}

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App />, document.getElementById('app'));

App.js

import React from 'react';

class App extends React.Component {
  render() {
      return (
         <div>
            <h2>Content</h2>
            <p>The content text!!!</p>
         </div>
      );
    }
}

export default App;

index.ejs within views folder

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Express React Redux</title>
    <link rel="stylesheet" href="../css/mystyles.css">
  </head>
  <body>

    <h1>Index Page</h1>
    <div id="app">

    </div>
    <script type="text/javascript" src="../bundle.js">

  </body>
</html>

Error Window

error_screen

package.json

{
  "name": "express_react_redux",
  "version": "1.0.0",
  "description": "simple react redux expressjs app",
  "main": "index.js",
  "scripts": {
    "webpack": "webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel": "^6.5.2",
    "babel-cli": "^6.22.2",
    "babel-core": "^6.22.1",
    "babel-loader": "^6.2.10",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.22.0",
    "ejs": "^2.5.5",
    "express": "^4.14.0",
    "pug": "^2.0.0-beta7",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-redux": "^5.0.2",
    "redux": "^3.6.0",
    "webpack": "^1.14.0"
  }
}
mpazitny commented 7 years ago

In webpack.config.js, you miss s in module: { loaderS. At least this was my issue with Webpack 2.

stalakokkula commented 7 years ago

I have the same problem My webpack.config.js looks like below

'use strict';
var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: './main.js',
  output: { path: __dirname, filename: 'bundle.js' },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};

here is my package.json file

{
  "name": "samplereact",
  "version": "1.0.0",
  "description": "test project",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Sreedhar Talakokkula",
  "license": "ISC",
  "dependencies": {
    "babel-polyfill": "6.23.0",
    "babel-runtime": "6.23.0",
    "react": "0.14.7",
    "react-dom": "0.14.7"
  },
  "devDependencies": {
    "babel-core": "6.4.5",
    "babel-loader": "^6.3.2",
    "babel-plugin-transform-runtime": "6.23.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.23.0",
    "webpack": "1.12.12"
  }
}

My main.js file

import Hello from './Hello.JSX';
import World from './World.JSX';

i get the following error

webpack-dev-server --progress --colors
http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from C:\Learning\Projects\React
loaderUtils.parseQuery() received a non-string value which can be problematic, see https://github.com/webpack/loader-utils/issues/56
parseQuery() will be replaced with getOptions() in the next major version of loader-utils.
Hash: 6d152ff83dc0a532b2cd
Version: webpack 2.2.1
Time: 15299ms
    Asset     Size  Chunks             Chunk Names
bundle.js  3.47 kB       0  [emitted]  main
chunk    {0} bundle.js (main) 826 bytes [entry] [rendered]
    [0] ./Hello.JSX 273 bytes {0} [built] [failed] [1 error]
    [1] ./World.JSX 273 bytes {0} [built] [failed] [1 error]
    [2] ./main.js 280 bytes {0} [built]

ERROR in ./Hello.JSX
Module parse failed: C:\Learning\Projects\React\Hello.JSX Unexpected token (6:9)
You may need an appropriate loader to handle this file type.
| class Hello extends React.Component {
|       render(){
|               return <h1>Hello</h1>
|       }
| }
 @ ./main.js 3:13-35

ERROR in ./World.JSX
Module parse failed: C:\Learning\Projects\React\World.JSX Unexpected token (6:9)
You may need an appropriate loader to handle this file type.
| class World extends React.Component {
|       render(){
|               return <h1>World</h1>
|       }
| }
loganfsmyth commented 7 years ago

@stalakokkula Your test regex is for lower-case .jsx but your files are .JSX it looks like.

pbarrientos commented 7 years ago

Hi, @stalakokkula, I got the same error and still not sure about the reason. I'm on node v7.7.2

Version: webpack 2.2.1
Time: 64ms
    Asset     Size  Chunks             Chunk Names
bundle.js  3.27 kB       0  [emitted]  main
   [0] ../src/client/app/index.jsx 289 bytes {0} [built] [failed] [1 error]

ERROR in ../src/client/app/index.jsx
Module parse failed: /RU/src/client/app/index.jsx Unexpected token (6:15)
You may need an appropriate loader to handle this file type.
| class App extends React.Component {
|     render() {
|         return <p>Hello World</p>;
|     }
| }

My index.jsx

import React from 'react';
import { render } from 'react-dom';

class App extends React.Component {
    render() {
        return <p>Hello World</p>;
    }
}

render(<App/>, document.getElementById('app'));

My webpack-config.js

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, './../src/client/public');
var APP_DIR = path.resolve(__dirname, './../src/client/app');

var config = {
    entry: APP_DIR + '/index.jsx',
    output: {
        path: BUILD_DIR,
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$ /,
                include: APP_DIR,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    }
};

module.exports = config;
loganfsmyth commented 7 years ago

Your test regex is broken: /\.jsx?$ / has an extra space at the end.

pbarrientos commented 7 years ago

Oh! Thanks, @loganfsmyth! I corrected the extra space and part of the error is gone :)

Version: webpack 2.2.1
Time: 409ms
    Asset     Size  Chunks             Chunk Names
bundle.js  3.86 kB       0  [emitted]  main
   [0] ../src/client/app/index.jsx 818 bytes {0} [built] [failed] [1 error]

ERROR in ../src/client/app/index.jsx
Module build failed: SyntaxError: Unexpected token (6:15)

  4 | class App extends React.Component {
  5 |     render() {
> 6 |         return <p>Hello World</p>;
    |                ^
  7 |     }
  8 | }
  9 |
loganfsmyth commented 7 years ago

If you post a repository that reproduces the issue we can take a look, but nothing jumps out at me that would be wrong.

rubyonrails3 commented 7 years ago

I had same issue today while I was experimenting with Redux tutorial from its site. I was using my custom directory structure.

functional-programming/ functional-programming/src/ functional-programming/components/ functional-programming/containers/

my index file was in

functional-programming/src/index.js

and that file was referring components

so I got error message that I need appropriate loader

then I've moved my components and containers folders into /src folder and everything begin to work okay for me.

P.S: I was using create-react-app

nidaibani21 commented 7 years ago

I am just starting out with react and have been facing similar issue

ERROR in ./dev/index.jsx Module parse failed: /Users/imran/Desktop/MyTotallyAwesomeApp/dev/index.jsx Unexpected token (7:6) You may need an appropriate loader to handle this file type. | render: function() { | return ( |

Hello, {this.props.greetTarget}!

| ); | }

package.json:

{ "name": "mytotallyawesomeapp", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "babel-core": "^6.24.0", "babel-loader": "^6.4.1", "babel-preset-es2015": "^6.24.0", "babel-preset-react": "^6.23.0", "react": "^15.4.2", "react-dom": "^15.4.2", "webpack": "^2.3.2" }, "babel": { "presets": [ "es2015", "react" ] } }

web pack.config.js:

var webpack = require("webpack"); var path = require("path");

var DEV = path.resolve(dirname, "dev"); var OUTPUT = path.resolve(dirname, "output");

var config = { entry: DEV + "/index.jsx", output: { path: OUTPUT, filename: "myCode.js" } }; module: { loaders: [{ include: DEV, loader: "babel-loader", }] }

module.exports = config;

where is the issue here?

pbarrientos commented 7 years ago

Hi again! @loganfsmyth Sorry for the delay, here is a repo with an example that reproduces the error. https://github.com/pbarrientos/new-react

I'm using node v7.8.0 and npm 4.2.0 After installing the packages I run: ./node_modules/.bin/webpack -d

This is what I get (now on webpack 2.3.2 same error): Module build failed: SyntaxError: Unexpected token (6:15)

Thanks in advance.

Couto commented 7 years ago

@pbarrientos I might be wrong, but I think the problem is not with webpack nor babel-loader, but with babel itself due to the way babel does lookup behaviour.

See this for more information https://babeljs.io/docs/usage/babelrc/#lookup-behavior

I could be wrong though.

pbarrientos commented 7 years ago

It seems you are right, @Couto I changed the structure of the project and the error is gone. I pushed these changes on the same repo if anyone wanna have a look, but I think the error was also reproducible when having the babel config in webpack.config.js instead of the previously "misplaced" .babelrc

Thank you all.

ujjwalvaish commented 7 years ago

I am facing the same issue, here's my webpack.config.js

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, './app/javascripts');

var config = {
  entry: APP_DIR + '/app1.jsx',
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js'
  }
};

 module : {
    loaders: [
      { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ }
    ]
  }

module.exports = config; 

Here's my babelrc:

{ "presets" : ["env", "react"] }

This is the error that I'm getting:

$

./node_modules/.bin/webpack -d Hash: 32205b71bab9f390005b Version: webpack 2.2.1 Time: 82ms Asset Size Chunks Chunk Names bundle.js 3.31 kB 0 [emitted] main [0] ./app/javascripts/app1.jsx 313 bytes {0} [built] [failed] [1 error]

ERROR in ./app/javascripts/app1.jsx Module parse failed: C:\Users\ujjwa\Desktop\app\javascripts\app1.jsx Unexpected token (5:11) You may need an appropriate loader to handle this file type. | class App extends React.Component { ...

loganfsmyth commented 7 years ago

The error is line 5 column 11, what is your code on that line?

ujjwalvaish commented 7 years ago

This is the line:

return <p..>Hello World</p..>; (I've put the .. to escape the formatting.)

loganfsmyth commented 7 years ago

And your .babelrc is in C:\Users\ujjwa\Desktop\app\.babelrc? You should check to make sure you don't have any other .babelrc files that might be confusing things.

ujjwalvaish commented 7 years ago

No .babelrc is on the Desktop i.e C:\Users\ujjwa\Desktop.babelrc (I'm using Desktop as an alias). And now I tried placing it in app folder, but that did not work as well. Here's my folder structure-

image

loganfsmyth commented 7 years ago

@ujjwalvaish Alright, I'd recommend you join our support channel on https://slack.babeljs.io/ so we can chat. There's too much noise on this issue as it is.

mrchief commented 7 years ago

This does not solve the error for me. Here's my config:

    rules: [
      {
        test: /\.jsx?$/,
        exclude: [/node_modules/, /\.test\.jsx?/],
        use: [{
          loader: 'babel-loader',
          options: {
            presets: ['react', ['es2015', {'modules': false}], 'stage-0'],
            plugins: [
              'syntax-dynamic-import',
              'lodash',
              'add-module-exports',
              'transform-decorators-legacy',
              ['transform-class-properties', { 'spec': true }]
            ]
          }
        }]
      }

I get a warning first and then the module parse error. Using react 15.4 and babel-loader v7

DISKONEKTeD commented 7 years ago

I believe you're not suppose to use "use" for babel-loader, see here:

https://webpack.js.org/guides/migrating/#module-loaders-is-now-module-rules

you want something like this instead:

    module: {
        rules: [
            {
                test:/\.js$/,
                include: SRC_DIR,
                loader: "babel-loader",
                options: {
                    presets: ['react', 'es2015', 'stage-2']
                }
            }

        ]
    }
mrchief commented 7 years ago

@DISKONEKTeD that is most likely a documentation bug. Either way, I tried use and got the same results.

ThinkCats commented 7 years ago

I get same error, because my webpack's entry config is error.


...
 entry: path.resolve(__dirname, 'app/main.js'),
...

My entry file name is main.js , but my component name is xxx.jsx .

I changed my entry file name to main.jsx, then everything is ok.

...
 entry: path.resolve(__dirname, 'app/main.jsx'),
...

If someone get the same error, this maybe is helpful.

My webpack.config.js:


var path = require('path');
var webpack = require('webpack');

var config = {
    entry: path.resolve(__dirname, 'app/main.jsx'),
    output: {
        path: __dirname + '/dist',
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {
        loaders: [{
            test: /\.jsx$/,
            exclude: /node_modules/,
            loaders: ['babel-loader?presets[]=react,presets[]=es2015'],
        }]
    }
};

module.exports = config;

And my package version :


  "dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-router": "^4.1.1",
    "zent": "^3.4.2"
  },
  "entry": {},
  "devDependencies": {
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-plugin-check-es2015-constants": "^6.22.0",
    "babel-plugin-transform-es2015-block-scoping": "^6.24.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.4",
    "less": "^2.7.2",
    "less-loader": "^4.0.5",
    "path": "^0.12.7",
    "style-loader": "^0.18.2",
    "webpack": "^3.2.0",
    "webpack-dev-server": "^2.5.1"
  }
aseem2625 commented 7 years ago

@ThinkCats Good for you. But I think, you don't need to do that necessarily to make it work. You tried using test: /\.js$/, instead of test: /\.jsx$/, ?

And it's always great to mention webpack version, you're using for someone to use your solution or for someone to point out anything.

MrRahulR commented 7 years ago

I'm working on a react code and it showing the similar error,

package.json

{
  "name": "myappv1",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www",
    "build": "node ./bin/webpack"
  },
  "dependencies": {
    "axios": "^0.16.2",
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "body-parser": "~1.17.1",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.3",
    "express": "~4.15.2",
    "jade": "~1.11.0",
    "morgan": "~1.8.1",
    "mysql": "^2.13.0",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-router": "^4.1.2",
    "serve-favicon": "~2.4.2",
    "webpack": "^3.3.0"
  }
}

webpack.config.js

var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'public');
var APP_DIR = path.resolve(__dirname, 'app');
var config = {
    entry: './index.jsx',
    output: {
        path: './',
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['.js', '.jsx']
        },
    module: {
        loaders: [
        {
                        test: /\.jsx?$/,
            loader: 'babel-loader',
            exclude: /node_modules/,
             query: {
                presets: ['es2015',  'react']
            }
                }
          ]
    }
}
module.exports = config;

It display error as below.

is1

aseem2625 commented 7 years ago

@MrRahulR even though you could be new to Git, you can check other people's formatting of code above and google it put code on git! Disappointed! Personally, I'm passing your query.

MrRahulR commented 7 years ago

@aseem2625 Everyone has dropped their code snippets above, I saw package.json and webpack.config.js I did same!

aseem2625 commented 7 years ago

@MrRahulR Downvoted for not acknowledging your improper editing, secretly editing your post and writing anti to it! Now, I'm totally ignoring your query.

MrRahulR commented 7 years ago

@aseem2625 Okay, I've expected some help here though thanks for your help! :1st_place_medal: :)

danez commented 7 years ago

Come on be friendly here. If you want to fight go somewhere else.

@MrRahulR As you are using webpack 3 your config is outdated. Read this migration guide which should cover all the cases you have. https://webpack.js.org/guides/migrating/#module-loaders-is-now-module-rules & https://webpack.js.org/guides/migrating/#what-are-options- Or have a look at our README in the usage section to see proper working configs: https://github.com/babel/babel-loader/#usage

MrRahulR commented 7 years ago

okay @danez, pushing few things in code from the urls worked for me. Thanks.

fitzgeraldsophie2 commented 6 years ago

I am facing the same issue.

webpack.config.js

var ExtractTextPlugin = require("extract-text-webpack-plugin");
var StaticSiteGeneratorPlugin = require('static-site-generator-webpack-plugin');
var autoprefixer = require('autoprefixer');
var ss = require('./src/ss_routes');

module.exports = {
  entry: './src/index',
  output: {
    path: 'build',
    filename: 'bundle.js',
    libraryTarget: 'umd'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: "babel-loader",
        include: __dirname + '/src',
      },
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract(
            'style-loader', // backup loader when not building .css file
            'css-loader!sass-loader' // loaders to preprocess CSS
        )
      },
      {
        test: /\.css/,
        loader: ExtractTextPlugin.extract(
          'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss'
        ),
        include: __dirname + '/src'
      },
      {
        test: /\.(jpg|png)/,
        loader: 'file-loader?name=assets/img-[hash:6].[ext]',
        include: __dirname + '/src'
      },
      {
        test: /\.(ico|otf|pdf)/,
        loader: 'file-loader?name=[name].[ext]',
        include: __dirname + '/src/'
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        include: __dirname + '/src/',
        loaders: [
          'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
          'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ]
      }
    ],
  },
  postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ],
  plugins: [
    new ExtractTextPlugin("styles.css"),
    new StaticSiteGeneratorPlugin('main', ss.routes, ss)
  ]
};

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import ReactDOMServer from 'react-dom/server'
import { Router, RouterContext, match, browserHistory, createMemoryHistory } from 'react-router'
import Template from './Template'
import Routes from './routes'

/* Client render (optional) */
if (typeof document !== 'undefined') {
  const outlet = document.getElementById('outlet')
  ReactDOM.render(<Router history={browserHistory} routes={Routes} />, outlet)
}

/* Exported static site renderer */
export default (locals, callback) => {
  const history = createMemoryHistory()
  const location = history.createLocation(locals.path)

  match({
    routes: Routes,
    location: location
  }, function(error, redirectLocation, renderProps) {
    var html = ReactDOMServer.renderToStaticMarkup(
      <Template>
        <RouterContext {...renderProps} />
      </Template>
    );
    callback(null, html)
  })
}

Error Window

image

package.json

{
  "name": "landing-page",
  "version": "1.0.0",
  "description": "An example static site using static-site-generator-webpack-plugin",
  "main": "src/index.js",
  "scripts": {
    "dev": "webpack-dev-server --hot --port 5000",
    "build": "webpack --config webpack.prod.config.js --progress -p"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/StevenIseki/static-site-generator-webpack-plugin-example"
  },
  "author": "SB",
  "license": "MIT",
  "dependencies": {
    "react": "^15.6.2",
    "react-dom": "^15.6.2",
    "react-router": "^2.8.1"
  },
  "devDependencies": {
    "amdefine": "^1.0.1",
    "async": "^2.5.0",
    "autoprefixer": "^6.7.7",
    "babel-core": "^6.26.0",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.25.0",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.9.0",
    "image-webpack-loader": "^3.4.2",
    "jquery": "^1.9.1",
    "neal-react": "^0.2.3",
    "node-sass": "^4.5.3",
    "popper.js": "^1.12.3",
    "postcss-loader": "^1.3.3",
    "sass-loader": "^4.1.1",
    "static-site-generator-webpack-plugin": "^3.4.1",
    "style-loader": "^0.13.2",
    "webpack": "^1.15.0",
    "webpack-dev-server": "^1.16.5"
  }
}
KostasTsiknas commented 6 years ago

For me it was something very silly. In my webpack.config.js I had the following line: exclude: /node_modules/ One of the parents of my working folder was node_modules e.g. C:\React\node_modules\MyProject\ As soon as I changed the folder structure removing node_modules from the parent folder, everything worked fine.

shubhamk54 commented 6 years ago

I have the same error above. Here is my wepack.config, I am still figuring out whats wrong in this.

`var webpack = require('webpack'); var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'C:\Users\DELL\Sample\src\client\public'); var APP_DIR = path.resolve(__dirname, 'C:\Users\DELL\Sample\src\client\app');

var config = { entry: APP_DIR + '/index.jsx', output: { path: BUILD_DIR, filename: 'bundle.js' } }; module : { loaders : [ { test : /.jsx?/, include : APP_DIR, loader : 'babel-loader', query: { presets: ['es2015'] } } ] };

module.exports = config; `

sinneren commented 6 years ago

@shubhamk54 use not query, use options. my working:

module: {
        rules: [
            {
                test: /\.jsx$/,
                exclude: /(node_modules|bower_components)/,
                use: [{
                    loader:'babel-loader',
                    options: {
                        presets: ['react', 'env']
                    }
                }]
            }
        ]
    }
mrchief commented 6 years ago

This error can happen for any of the 100s of loaders failing. Do remember that this a closed issue. You'll have a better chance at getting your query resolved by posting to stackoverflow.com or opening a new issue with specifics.

serjo96 commented 6 years ago

Have same problem

i use regelar expression in component react

console.log( '_asdasdas/'.match(/(?<=\_)(.*?)(?=\/)/g))

but compiler show me this erorr

ERROR in ./src/components/MediaList/GenresList.jsx
Module parse failed: D:\work\move-search\node_modules\babel-loader\lib\index.js!D:\work\move-search\src\components\MediaList\GenresList.jsx Error parsing regular expression: Invalid regular expression: /(?<=\_)(.*?)(?=\/)/: Invalid group (150:35)
You may need an appropriate loader to handle this file type.
|               idRequest = this.props.match.params.id.split('-').pop(),
|               typeRequest = 'movie';
|           console.log('_asdasdas/'.match(/(?<=\_)(.*?)(?=\/)/g));
|           if (this.props.location.search) {
|               if (pageNubmer <= 2) {
 @ ./src/Routes/Routes.jsx 85:18-63
 @ ./src/App.jsx
 @ ./src/index.jsx
 @ multi (webpack)-dev-server/client?http://127.0.0.1:8888 webpack/hot/dev-server react-hot-loader/patch ./src/index.jsx

webpack config

"use strict";
var webpack = require('webpack');
var path = require('path');
var loaders = require('./webpack.loaders');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

const HOST = process.env.HOST || "127.0.0.1";
const PORT = process.env.PORT || "8888";

loaders.push({
  test: /\.sass$/,
  loaders: ['style-loader', 'css-loader?importLoaders=1', 'resolve-url-loader', 'sass-loader?sourceMap'],
  exclude: ['node_modules']
});

module.exports = {
  entry: [
    'react-hot-loader/patch',
    './src/index.jsx', // your app's entry point
  ],
  devtool: process.env.WEBPACK_DEVTOOL || 'eval-source-map',
  output: {
    publicPath: '/',
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    loaders
  },
  devServer: {
    contentBase: "./public",
    // do not print bundle build stats
    noInfo: true,
    // enable HMR
    hot: true,
    // embed the webpack-dev-server runtime into the bundle
    inline: true,
    // serve index.html in place of 404 responses to allow HTML5 history
    historyApiFallback: true,
    port: PORT,
    host: HOST
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new ExtractTextPlugin({
      filename: 'style.css',
      allChunks: true
    }),
    new DashboardPlugin(),
    new HtmlWebpackPlugin({
      template: './src/template.html',
      files: {
        css: ['style.css'],
        js: [ "bundle.js"],
      }
    }),
  ]
};

jsx loader

{ test: /\.jsx?$/, exclude: /(node_modules|bower_components|public\/)/, loader: "babel-loader" }

.babelrc

{
  "presets": ["es2015", "react", "stage-0"],
  "plugins": ["transform-runtime", "transform-decorators-legacy", "transform-class-properties", "react-hot-loader/babel", "transform-es2015-unicode-regex"]
}
amorenew commented 6 years ago

I have same issue details on StackOverflow https://stackoverflow.com/questions/48034538/how-to-solve-this-error-you-may-need-an-appropriate-loader-to-handle-this-file-t

shashankKeshava commented 6 years ago

I'm facing a similar error. Still not able to fix it

Error:

ERROR in ./src/index.js
Module parse failed: Unexpected token (6:12)
You may need an appropriate loader to handle this file type.
|     render() {
|         return (
|             <div>
|                 <h1>Welcome to React Boilerplate</h1>
|             </div>

Webpack Config:

'use strict';

const webpack = require('webpack');
const htmlWebpack = require('html-webpack-plugin');

const commonPaths = require('./common-paths');
console.log(commonPaths.srcPath);
module.exports = {
    // Entry: First file webpack starts(your dependency graph)
    entry: {
        app: commonPaths.inputPath,
    },
    // Output: How and where to put bundles and format them
    output: {
        filename: 'bundle.js',
        path: commonPaths.outputPath,
    },
    // Loaders:  How to treat files before adding to dependency graphs
    module: {
        loaders: [
            {
                test: /\.(js|jsx)$/,
                include: [commonPaths.inputPath],
                loader: ['babel-loader'],
                query: {
                    presets: ['es2015', 'react'],
                    plugins: ['transform-runtime'],
                },
                options: {
                    cacheDirectory: true,
                },
            },
        ],
        rules: [
            {
                test: /\.png$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 1000,
                        },
                    },
                ],
            },
        ],
    },
    // Plugins: Extremely Customisable
    plugins: [new webpack.ProgressPlugin(), new htmlWebpack()],
};

The entire project is available at React-Redux-BoilerPlate

lalitmee commented 6 years ago

I am getting the same error and now I am getting frustrated. I searched a lot to remove this error but no luck. Please help me.

const path = require("path"); const webpack = require("webpack"); const webpackTargetElectronRenderer = require("webpack-target-electron-renderer");

let options = { module: { rules: [ { test: /.js$/, loaders: ["babel-loader"], exclude: /node_modules/, query: { presets: ["es2015", "react", "stage-0"] } }, { test: /.jsx?$/, loaders: ["babel-loader"], query: { presets: ["es2015", "react"] }, exclude: /node_modules/ }, { test: /.css$/, use: [ { loader: "style-loader" }, { loader: "css-loader" } ], include: /node_modules/ } ] }, output: { path: path.join(__dirname, "public", "js"), filename: "bundle.js" }, resolve: { extensions: ["", ".js", ".jsx"], packageMains: [ "webpack", "browser", "web", "browserify", ["jam", "main"], "main" ] }, entry: ["./app/app.js"], debug: true };

options.target = webpackTargetElectronRenderer(options);

module.exports = options;

- **package.json**

{ "name": "scotch-player", "productName": "Scotch Player", "version": "1.0.0", "description": "Scotch Demo Player", "main": "main.js", "scripts": { "test": "npm test", "start": "electron main.js", "electron": "webpack && electron .", "web": "webpack -—target web && webpack-dev-server --target web" }, "dependencies": { "babel-preset-es2015": "^6.6.0", "babel-preset-es2017": "^6.24.1", "babel-preset-react": "^6.5.0", "babel-preset-stage-0": "^6.24.1", "babelify": "^7.3.0", "css-loader": "^0.28.9", "electron-prebuilt": "^0.36.0", "electron-reload": "^0.2.0", "jquery": "^2.2.3", "react": "^0.14.8", "react-dom": "^0.14.7", "semantic-ui-css": "^2.2.14", "semantic-ui-react": "^0.78.2", "style-loader": "^0.20.1", "webpack-dev-server": "^2.11.1" }, "devDependencies": { "babel-core": "^6.4.5", "babel-loader": "^6.2.1", "minimist": "^1.2.0", "webpack": "^1.12.12", "webpack-target-electron-renderer": "^0.4.0" } }


- **.bablerc**

{ "presets":[ "es2015", "react", "stage-0" ], "plugins": ["transform-class-properties"] }

- **error message when I am running**  `npm run electron`
```bash
Hash: a15466a376457c6f3383
Version: webpack 1.12.12
Time: 145ms
    Asset     Size  Chunks             Chunk Names
bundle.js  1.51 kB       0  [emitted]  main
   [0] multi main 28 bytes {0} [built] [1 error]
   [1] ./app/app.js 0 bytes [built] [failed]

ERROR in ./app/app.js
Module parse failed: /home/lalit/Desktop/Github/Electron/simple-electron/scotch-player/app/app.js Line 3: Unexpected token
You may need an appropriate loader to handle this file type.
| // ES6 Component
| 
| import React from "react";
| import ReactDOM from "react-dom";
| import { Header, Button, Container } from "semantic-ui-react";
 @ multi main

I have tried a lot. Please help me. Thank you.

MarkOGDev commented 6 years ago

Try removing the line exclude: /node_modules/ in your loaders. That worked for my similar Module parse failed: issue.

danielrob commented 6 years ago

Although this issue is closed, it is easily found via google, so adding my solution in case it helps.

For me babel was configured in package.json and the env.production.only key was too restrictive after a refactor.

Updating to e.g.

  "babel": {
     "presets": [ ... ]
    "env": {
      "production": {
        "only": [
          "app1",
          "app2",
          "common"
        ],
...

Solved my problem. This may apply to you even if your babel options are configured elsewhere.