【发布时间】:2021-12-31 10:27:57
【问题描述】:
我的目标是在我构建的整个 react-app 中使用 ES6 语法(或最新的语法)。
我已经设法通过省略一些 babel 依赖项(例如 @babel/preset-env)来避免在我自己的代码中使用 polyfill。
我的捆绑文件在大多数情况下确实包含ES5 语法。我假设 babel(或 webpack?)是 polyfilling react 和 webpack 的 runtime 到 ES5 以实现浏览器兼容性。
另一种选择可能是 webpack 的运行时本机应该使用 ES5 并且不能转换为 ES6(当前持续的可能性,请参阅答案)。
这是我的package.json:
"main": "index.js",
"scripts": {
"start": "webpack serve --mode=development --open",
"build": "webpack --mode=production"
},
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"@babel/preset-react": "^7.16.5",
"babel-loader": "^8.2.3",
"css-loader": "^6.5.1",
"html-webpack-plugin": "^5.5.0",
"style-loader": "^3.3.1",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.7.2"
},
"babel": {
"presets": [ "@babel/preset-react" ]
}
这是我的webpack.config.js:
const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = {
output: {
path: path.resolve(__dirname, "build"),
filename: "[name].js"
},
resolve: {
modules: [ path.join(__dirname, "src"), "node_modules" ],
alias: {
react: path.join(__dirname, "node_modules", "react")
}
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" }
]
}
]
},
plugins: [
new HtmlWebPackPlugin({ template: "./src/index.html" })
],
};
我使用的不是create-react-app,而是我自己的样板和配置。
我的index.js、app.js、index.html、styles.css 位于./src 文件夹中。
感谢您的帮助
【问题讨论】:
-
尽管这个问题已经得到了官方的回答,但我的帖子仍然活跃并关注有关 Webpack 在应用程序包中使用 ES6 语法的更新。
标签: javascript reactjs webpack babeljs babel-polyfill