I'm pretty new to Webpack, and I'm just trying to get a simple project off the ground here. I'm getting the following error:
ERROR in ./index.js
Module parse failed: /Users/jay/Documents/personal_projects/open_phil_grants_visualizer/index.js Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
| import App from './app';
|
| ReactDOM.render(<App />, document.getElementById('content'));
|
@ multi (webpack)-dev-server/client?http://localhost:8080 ./index.js
Here is my webpack.config.js:
module.exports = {
entry: './index.js',
output: {
path: __dirname,
filename: 'bundle.js'
},
devtool: 'source-map'
};
the dependencies in my package.json:
"dependencies": {
"d3": "^4.9.1",
"lodash": "^4.17.4",
"react": "^15.6.1",
"react-d3-basic": "^1.6.11",
"react-dom": "^15.6.1"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"webpack-dev-server": "^2.4.5"
}
Here is my index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
ReactDOM.render(<App />, document.getElementById('content'));
here is app.js:
import React from 'react';
class App extends React.Component {
render() {
return(
<h2>
Hello from the App component!
</h2>
)
}
}
export default App;
How can I get this thing going?
You're going to need to set up your loader rules to actually process and transpile your files to browser compatible ES5. Webpack does not automatically convert your ES2015 and JSX code to be web-compatible, you have to tell it to apply a loader to certain files to transpile them to web-compatible code, as the error states. Since you don't do this, the error happens.
Assuming you have Webpack version 2+, use the rules property in the configuration:
module.exports = {
entry: './index.js',
output: {
path: __dirname,
filename: 'bundle.js'
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.jsx?/,
include: 'YOUR_APP_SRC_DIR',
use: {
loader: 'babel-loader',
options: {
presets: ['es2015', 'react']
}
}
}
]
}
};
This adds a rule to the Webpack config that uses the RegEx in test to select files that end in .js or .jsx. Then it uses babel-loader with the presets es2015 and react to use Babel and transpile your JSX and ES2015 code to ES5 code. You will also need to install the following packages:
babel-corebabel-loaderbabel-preset-reactAnd you can get rid of:
babel-cliMore info at the Webpack documentation for modules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With