Webpack入门,导入错误

时间:2016-11-23 23:43:24

标签: javascript html 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>

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() );

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

如何让它正常运行?

1 个答案:

答案 0 :(得分:5)

如上所述,您需要设置Babel才能使其正常运行。

安装babel dependancies:

    npm install --save-dev babel-loader babel-core babel-preset-react babel-preset-es2015

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

var webpack = require('webpack');

module.exports = {
  ...
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};