0

Given

import test from './test.js';
import test2 from './test.mjs';

and test.js and test.mjs both containing

class A {
    test() {
        console.log('from mjs'); // or console.log('from js');
    }
}
export default A;

Babel transpiles

  [...];

  (0, _createClass2.default)(A, [{
    key: "test",
    value: function test() {
      console.log('from js');
    }
  }]);

  [...]

  class A {
    test() {
        console.log('from mjs');
    }
  }

  [...]

How should I configure babel to treat *.mjs files exactly like *.js files. I need them to be *.mjs files so that I can run it in node without transpilation.

Plugins I am currently explicitly adding are

'@babel/plugin-proposal-class-properties', '@babel/plugin-transform-runtime', '@babel/plugin-transform-classes'
David Mulder
  • 26,123
  • 9
  • 51
  • 114
  • @T.J.Crowder Babel version: `7.0.0-beta.46`, and the last plugin is `transform-classes` or am I misunderstanding you? (I am sorry, my experience has been primarily with traceur before Babel won the transpiler wars) – David Mulder May 02 '18 at 11:07
  • @T.J.Crowder Well, they have been moving everything to the `@babel` namespace. When you check the `es2015-classes` npm package the referenced github is a 404, as it has been moved to the new system. – David Mulder May 02 '18 at 11:18
  • Anyway, the class compilation clearly works by itself, it's just that somehow `*.mjs` files get treated different and thus not transpiled. I have been wondering whether it might have to do with https://github.com/babel/babel/pull/5700 – David Mulder May 02 '18 at 11:19
  • Sounds like the plugin name was a red herring then. Good luck! – T.J. Crowder May 02 '18 at 11:23
  • Is it not transforming the class syntax only, or nothing at all for the .mjs files? If the latter is true, you might want to check the babel-loader options in the webpack config to make sure it's also running babel against mjs files. – Elian Ibaj May 03 '18 at 18:27
  • @ElianIbaj just classes, everything else is being transformed – David Mulder May 03 '18 at 20:18
  • could you share your webpack config? – Elian Ibaj May 04 '18 at 15:18
  • 1
    @DavidMulder Almost two years later, I am having exactly the same problem. May I ask how you solved it? Thanks – foresightyj Mar 18 '20 at 02:41
  • 1
    @foresightyj read my answer below, hope this helps – Attenzione Jun 03 '21 at 09:47

1 Answers1

1

You need to add *.mjs extension to your Webpack configuration:

  module: {
    rules: [
      {
        test: /\.m?js$/,
        use: {
          loader: 'babel-loader',
          options: {
            // ...
Attenzione
  • 833
  • 9
  • 12