reactjs - 我应该通过 .babelrc 还是 WebPack 配置 Babel?

标签 reactjs webpack babeljs

在我的 React 项目中,webpack.config.js 引入了提案类属性,如下所示:

...
module: {
  rules: [
    {
      test: /\.jsx?$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader',
        query: {
          presets: ['@babel/react', '@babel/preset-env'],
          plugins: ['@babel/proposal-class-properties']
        }
      },
    }
...

通过包含 @babel/proposal-class-properties,我可以从我的 React 组件等中删除构造函数。

然而,documentation.babelrc 中显示 plugin-proposal-class-properties 如下(完全没有提及 webpack.config.js):

{
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

而我的 .babelrc 根本不包含任何插件:

{
  "presets": [
    ["@babel/env", {
      "modules": false
    },
    "@babel/preset-env"]
  ]
}

webpack.config.js 中包含插件(例如 proposal-class-properties)与将它们放在 中有什么有效的区别? .babelrc?

最佳答案

你可以通过.babelrc或者通过webpack中的babel-loader配置来配置babel。 它们的工作原理完全相同。

但是,我建议只使用 .babelrc 来配置 babel。 这样它也可以在你运行测试时工作,通常不会通过 webpack,因此不会有 babel 的 webpack 配置。

.babelrc:

{
  "presets": ["@babel/preset-env"]
  "plugins": ['@babel/plugin-proposal-class-properties', {'loose': true}]
}

关于reactjs - 我应该通过 .babelrc 还是 WebPack 配置 Babel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56463846/

相关文章:

reactjs - React App 刷新后返回错误

javascript - 单击时显示 react 组件

node.js - 使用命令行参数运行 webpack

reactjs - ReactJS 中生产和开发构建的区别

ecmascript-6 - FlowType 是否支持混合或组合?

javascript - nodemon,babel-node : how to set environment variable?

reactjs - 使用 babel CLI 找不到相对于目录的预设 "env"

javascript - react Hook setState 参数

javascript - 部署到 firebase 托管的 ReactJS 应用程序在首次部署后未更新

webpack-dev-server 不工作找不到模块 '../lib/polyfills'