我正在开始使用 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/[email protected] /cdn-cgi/l/email-protection" 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>
The 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
我怎样才能让它正确运行?
正如所建议的,您需要设置 Babel 才能使其正常工作。
安装 babel 依赖项:
npm install --save-dev babel-loader babel-core babel-preset-react babel-preset-es2015
您需要编辑您的webpack.config.js
文件包含 babel loader 设置:
var webpack = require('webpack');
module.exports = {
...
module: {
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
},
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)