How do I get Webpack to transpile ES6 code?

后端 未结 1 985
盖世英雄少女心
盖世英雄少女心 2021-01-03 11:51

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 pa         


        
相关标签:
1条回答
  • 2021-01-03 12:19

    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.

    0 讨论(0)
提交回复
热议问题