Webpack入门,导入错误

ero*_*msr 3 html javascript npm webpack babeljs

我开始使用Webpack,但已遇到以下问题:我创建了一个app/index.js文件(如文档中所述).我还创建了一个index.html文件(从文档中复制了HTML和CSS).我在CLI中运行了正确的命令(包括生成dist/bundle.js文件).

代码:

<!DOCTYPE html>
<html lang="nl">
    <head>
        <meta charset="UTF-8">
        <title>Webpack</title>
        <!-- <script src="https://unpkg.com/lodash@4.16.6" type="text/javascript"></script> -->
        <script src="dist/bundle.js" type="text/javascript"></script>
    </head>
    <body>
        <!-- Markup here -->
        <div id="root"></div>

        <!-- <script src="app/index.js" type="text/javascript"></script> -->
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

JS:

// To bundle the lodash dependency with the index.js, we need to import lodash.
import _ from 'lodash';

function component () {
    var element = document.createElement( 'div' );

    /* lodash is required for the next line to work */
    element.innerHTML = _.map( [ 'Hello, webpack' ], function( item ) {
        return item + ' ';
    });

    return element;
}

document.body.appendChild( component() );
Run Code Online (Sandbox Code Playgroud)

这将返回以下控制台错误: bundle.js:48 Uncaught SyntaxError: Unexpected token import

如何让它正确运行?

Pin*_*eda 5

正如已经建议的那样,你需要设置Babel以使其正常工作.

安装babel dependancies:

    npm install --save-dev babel-loader babel-core babel-preset-react babel-preset-es2015
Run Code Online (Sandbox Code Playgroud)

您需要编辑webpack.config.js文件以包含babel加载程序设置:

var webpack = require('webpack');

module.exports = {
  ...
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};
Run Code Online (Sandbox Code Playgroud)