Webpack入门,导入错误 [英] Webpack getting started, import error

查看:193
本文介绍了Webpack入门,导入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm getting started with Webpack, but already ran into the following problem: I created an app/index.js file (as specified in the documentation). I also created an index.html file (copied the HTML and CSS from the documentation). I ran the correct commands in the CLI (including generating a dist/bundle.js file).

代码:

The code:

<!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:意外的令牌导入

This returns the following console error: bundle.js:48 Uncaught SyntaxError: Unexpected token import

如何让它正确运行?

推荐答案

如前所述,您需要安装Babel才能正常工作。

As has been suggested, you'll need to setup up Babel to get this working.

安装babel依赖关系:

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

您需要编辑 webpack.config.js file来包含babel加载器设置:

You'll need to edit your webpack.config.js file to include the babel loader settings:

var webpack = require('webpack');

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

这篇关于Webpack入门,导入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆