Home > Enterprise >  How to use babel-loader with native es6 modules?
How to use babel-loader with native es6 modules?

Time:09-18

I'm use native es6 modules on static site.

<script type="module" src="./main.js"></script>

Before deploying, I pass js files through babel

// webpack.config.js

rules: [
  {
    test: /\.js$/i,
    exclude: /node_modules/,
    use: ['babel-loader'],
  }
]

// .babelrc

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

By default babel turns modules into common js, although I have a flag "modules": false in my .babelrc

I don't want babel to turn modules into commonjs, I just want to turn everything except import and export in es2015, so that I can use native modules in the browser

Like this: // main.js before

export default () => {
  return 'Hello world!'
}

// main.js after babel

export default function () {
  return 'Hello world!'
}

According to the documentation babel provides a module: false option, but it doesn't work for me

Also, not working caller with supportsStaticESM

  {
    test: /\.js$/i,
    exclude: /node_modules/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: ['@babel/preset-env'],
        caller: {
          supportsStaticESM: true
        }
      }
    }
  }

However, when I use babel-cli I get what I need!

i think webpack is not friendly with babel in this case

Thanks.

"babel-loader": "8.0.5"
"webpack": "^5.40.0"

CodePudding user response:

For me just specifying target did the trick.

module.exports = {
    entry: './js/index.js',
    // ...
    target: ['web', 'es5']
}

CodePudding user response:

If it works with Babel but not with Webpack, then most likely Webpack configuration overrides setting from Babel.

Please try to remove presets: ['@babel/preset-env'], from Webpack config (if present).

  • Related