[英]Use Babel with JavaScript
I am trying to write my first babel program and kind of stuck. 我正在尝试编写我的第一个babel程序,有点卡住了。
var message = "Hello World";
module.exports = message;
var message = require('./script1');
document.write(`This is formatted with ES6 ${message}`);
module.exports = {
entry: {
main: [
'./script1.js',
'./script2.js'
]
},
output: {
filename: "./public/[name].js"
},
loaders: {
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
}
}
The above code works and I am able to see the output but now if I modify script2 to 上面的代码有效,我能够看到输出,但是现在如果我将script2修改为
import message from './script1';
document.write(`This is formatted with ES6 ${message}`);
then when I run webpack it says 然后当我运行webpack时说
ERROR in ./script2.js
Module parse failed: /Users/a.c/MyProjects/ReactTutorial/script2.js Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import message from './script1';
| document.write(`This is formatted with ES6 ${message}`);
@ multi main
My understanding is that because I am using babel, I should be able to use the new ES6 way of importing stuff into my code easily. 我的理解是,因为我正在使用babel,所以我应该能够使用新的ES6方法轻松地将内容导入代码中。
Try add resolve.extensions
to config file (in order to avoid always write extensions when you import .js
or .jsx
files) also if you are using babel 6
you need install couple packages babel-preset-es2015
and babel-preset-react
尝试将
resolve.extensions
添加到配置文件中(以避免在导入.js
或.jsx
文件时始终写扩展名),如果您正在使用babel 6
,则需要安装几个软件包babel-preset-es2015
和babel-preset-react
module.exports = {
entry: {
main: [
'./script1.js',
'./script2.js'
]
},
output: {
filename: "./public/[name].js"
},
loaders: {
test: /\.jsx?$/, // or /\.(js|jsx)$/
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
},
resolve: {
extensions: ['', '.js', '.jsx']
}
}
Most likely you have forgotten to specify es2015 preset
for babel. 您很可能忘记了为babel指定
es2015 preset
。
Make sure it's installed: 确保已安装:
> npm i -D babel-preset-es2015
You have two options to specify this preset for babel. 您有两个选项可为babel指定此预设。
Create .babelrc
file and specify the preset there: 创建
.babelrc
文件并在此处指定预设:
{ "presets": ["es2015"] }
Specify the preset using query
property : 使用
query
属性指定预设:
module: { loaders: [ { test: /\\.jsx?$/, include: /src/, loader: 'babel', query: { presets: ['es2015'] } } ] }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.