强制Webpack在react应用bundle中使用ES6语法



我的目标是在我的整个react应用程序中构建ES6语法(或最新语法(

我已经通过省略一些babel依赖项(如@babel/preset-env(,在自己的代码中避免了polyfill。

但是,我的捆绑文件在很大程度上包含ES5语法。我假设babel(或webpack?(是polyfilling react,并且为了浏览器兼容性,webpack的运行时是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.jsapp.jsindex.htmlstyles.css都在./src文件夹中。

感谢您的帮助

如果您没有使用@babel/preset-env,那么您的代码在默认情况下不应该更改。只有react应该被转换为es5(主要是JSX转换(。你可能提到了webpack添加的样板代码,它可以在es5中。

您可以在您的webpack配置中使用optimization: { minimize: false },以便更好地查看您的捆绑包。

webpack的这些样板被称为运行时。

没有办法强制webpack使用一组功能,但您可以强制它NOT使用抛出的output.environment.*的一组功能。例如,对于下面的代码,您说不要在运行时代码中使用const

...
output: {
    environment: {
        const: false
    }
}
...

最新更新