How do I get Webpack to transpile ES6 code?

偶尔善良 提交于 2019-12-18 13:38:00

问题


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?


回答1:


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-core
  • babel-loader
  • babel-preset-react

And you can get rid of:

  • babel-cli

More info at the Webpack documentation for modules.



来源:https://stackoverflow.com/questions/44742106/how-do-i-get-webpack-to-transpile-es6-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!