webpack可以将js转es6吗?
webpack can convert js to es6?
我使用 webpack 来捆绑我的节点应用程序。
我在包中看到了 webpack 从 const
转换为 var
的结果。这意味着 webpack 将我的文件转换为 es5。
如何告诉 webpack 转换为 es6? (保持常量不变 and/or 例如使用 import 关键字)
app.js
import {test} from './some';
const x = 1;
console.log('test', test);
console.log('this should be const in the bundle, not var. ', x);
捆绑包是:
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _some__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./some */ "./some.js");
var x = 1;
console.log('test', _some__WEBPACK_IMPORTED_MODULE_0__["test"]);
console.log('this should be const in the bundle, not var. ', x);
/***/ }),
我的 webpack 配置:
const path = require('path');
module.exports = () => [
{
mode: 'development',
entry: path.resolve(__dirname, './app.js'),
output: {
path: path.resolve(__dirname, './dist')
},
devtool: 'source-map',
target: 'node',
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
}
];
您使用的 @babel/preset-env 没有任何选项。这会将代码转换为 ES5,文档中说不建议以这种方式使用它。 "env" 预设的全部要点是您提供一个目标平台,它会自动应用该平台所需的转换。传递 "targets.node"-option 值 true 或 "current" 将转换当前使用的节点版本的代码。使用带有此选项的预设还有一个额外的好处,如果新的 node.js 支持更多使用的 ES 功能,那么升级 node.js 不需要更改 Babel 配置并且转换的代码更少。 =12=]
node.js 中对 ECMAScript 模块的支持仍处于试验阶段,但您可以通过将 false 传递给 "modules"-选项来禁用模块转换。
options: {
presets: [[
'@babel/preset-env',
{
targets: {
node: "current"
},
modules: false
}
]]
}
我使用 webpack 来捆绑我的节点应用程序。
我在包中看到了 webpack 从 const
转换为 var
的结果。这意味着 webpack 将我的文件转换为 es5。
如何告诉 webpack 转换为 es6? (保持常量不变 and/or 例如使用 import 关键字)
app.js
import {test} from './some';
const x = 1;
console.log('test', test);
console.log('this should be const in the bundle, not var. ', x);
捆绑包是:
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _some__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./some */ "./some.js");
var x = 1;
console.log('test', _some__WEBPACK_IMPORTED_MODULE_0__["test"]);
console.log('this should be const in the bundle, not var. ', x);
/***/ }),
我的 webpack 配置:
const path = require('path');
module.exports = () => [
{
mode: 'development',
entry: path.resolve(__dirname, './app.js'),
output: {
path: path.resolve(__dirname, './dist')
},
devtool: 'source-map',
target: 'node',
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
}
];
您使用的 @babel/preset-env 没有任何选项。这会将代码转换为 ES5,文档中说不建议以这种方式使用它。 "env" 预设的全部要点是您提供一个目标平台,它会自动应用该平台所需的转换。传递 "targets.node"-option 值 true 或 "current" 将转换当前使用的节点版本的代码。使用带有此选项的预设还有一个额外的好处,如果新的 node.js 支持更多使用的 ES 功能,那么升级 node.js 不需要更改 Babel 配置并且转换的代码更少。 =12=]
node.js 中对 ECMAScript 模块的支持仍处于试验阶段,但您可以通过将 false 传递给 "modules"-选项来禁用模块转换。
options: {
presets: [[
'@babel/preset-env',
{
targets: {
node: "current"
},
modules: false
}
]]
}