neoshinesnh
neoshinesnh

Reputation: 25

Babel not transpiling class (Webpack)

I'm using babel + webpack to transpiled the code. Some codes are transpiling, as arrows functions, however others no, like classes that should be transformed.

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:

  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

Upvotes: 1

Views: 2411

Answers (2)

neoshinesnh
neoshinesnh

Reputation: 25

I found my problem. A package in node_modules generated the error. In the exclude property I ignored this package, which transformed it.

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

Upvotes: 1

Grzegorz T.
Grzegorz T.

Reputation: 4113

.babelrc - unambiguous

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

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

Upvotes: 0

Related Questions