0
votes

I am trying to use ES6 imports with Express Node.js. I know that Node.js supports CommonJS only so I have configured Babel with Webpack 4 like such:

{
      test: /\.m?js$/,
      exclude: ['/node_modules/', /\bcore-js\b/, /\bwebpack\/buildin\b/, /@babel\/runtime-corejs3/],
      use: {
        loader: 'babel-loader',
        options: {
          babelrc : false,
          sourceType : "unambiguous",
          presets : [
            ["@babel/preset-env", {
              modules : false,
              useBuiltIns : "usage",
              corejs : {
                version : "2", 
              }
            }]
          ],
        }
      }
    },

As a test to see if it works I updated my CommonJS require statements into ES6 imports like such:

import express from "express"
import api from "api/v1/index.api.js"

const expressRouter = express.Router();

expressRouter.get('/', async function (req, res)  {
});

export default expressRouter

I believe having read this article that the above should just work. But on build, I still get the following error:

import express from "express"

^^^^^^

SyntaxError: Cannot use import statement outside a module

Is my babel-loader not working, or is there some other issue going on? Firstly not all my files are using ES6 imports - some are still using CommonJS require statements. I thought I'd try it on one file at a time to ensure it works which sadly it does not.

Any ideas on what to look at? I am using core-js 2.6.11 because version 3 causes problems with mini-css-extract-plugin

1

1 Answers

1
votes

@babel/plugin-transform-modules-commonjs did work for me where I needed the some commonjs lib to be used for setting up the test infrastructure. Note to add it in babel.config.js