简体   繁体   English

Babel 不转译类(Webpack)

[英]Babel not transpiling class (Webpack)

I'm using babel + webpack to transpiled the code.我正在使用 babel + webpack 来转译代码。 Some codes are transpiling, as arrows functions , however others no, like classes that should be transformed.一些代码正在转换,如arrows functions ,但其他代码没有,比如应该转换的classes

The following code is not being transpiled:以下代码没有被转译:

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

Follows the webpack config's:遵循 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'] } }],
            ],
          },
        }]
      }
    ]
  },

The expected result should be: example on babeljs预期结果应该是: babeljs 上的例子

I found my problem.我发现了我的问题。 A package in node_modules generated the error. node_modules一个包产生了错误。 In the exclude property I ignored this package, which transformed it.exclude属性中,我忽略了这个包,它改变了它。

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'] } }],
            ],
          },
        }]
      }
    ]
  },

.babelrc - unambiguous .babelrc -明确

{
  "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
},

script - For the purpose of the test I added the constructor with the alert脚本- 为了测试的目的,我添加了带有警报的构造函数

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

index.html - in index.html invoked our test class index.html - 在 index.html 中调用了我们的测试类

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM