Babel不转译类(Webpack)

时间:2019-07-12 18:48:40

标签: javascript webpack babeljs

我正在使用babel + webpack来编译代码。 有些代码正在以arrows functions的形式进行转码,而另一些则没有,例如classes应该进行转换。

以下代码没有被编译:

module.exports = class {
  static setMetric(name, value) {;
    if (typeof ga === 'function') {
      ga('set', name, value);
    }
  };
}

遵循webpack配置:

  module: {
    rules: [
      { 
        test: /\.js$/, 
        exclude: /(node_modules|bower_components)/,
        use: [{
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env', { targets: { browsers: ['ie >= 11', 'safari > 9'] } }],
            ],
          },
        }]
      }
    ]
  },

预期结果应为:example on babeljs

2 个答案:

答案 0 :(得分:0)

.babelrc -unambiguos

{
  "presets": [
    [
     "@babel/preset-env",
    ]
 ],
   "sourceType": "unambiguous" // important
 }

Webpack

output: {
  path: path.resolve(__dirname, 'dist'),
  filename: './script.js',
  library: 'test' // of course, it can be a different name
},

脚本-为了进行测试,我在构造函数中添加了警报

module.exports = class {
  constructor() {
    alert('ok')
  }
  static setMetric(name, value) {
    if (typeof ga === 'function') {
      ga('set', name, value);
    }
  };
 }

index.html -在index.html中调用了我们的测试类

<script src="./script.js"></script>
<script>
  new test();
</script>

答案 1 :(得分:0)

我发现了问题。节点模块上的软件包,生成了错误。 在排除属性上,我忽略了此程序包以对其进行转换

module: {
    rules: [
      { 
        test: /\.js$/, 
        exclude: /(node_modules(?!\/packageNameToTransform\/)|bower_components)/,
        use: [{
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env', { targets: { browsers: ['ie >= 11', 'safari > 9'] } }],
            ],
          },
        }]
      }
    ]
  },
相关问题