Search code examples
node.jsbabeljscommonjs

Using babel with preset-env on a small node project, unable to convert import/export statements to commonjs


I'm trying to set up a node project so I can use the common import/export syntax, and for compatibility, use babeljs to convert the import and export statements to requires.

When I try transpiling using babel though, I'm not seeing any changes and I don't know why.

Here's my babel.config.js

// babel.config.js
module.exports = {
  // I thought this was what I would need to add for making the changes, based on the docs
  plugins: ["@babel/plugin-transform-modules-commonjs"],


  // env takes care of the majority of changes I might need to convert code to make
  // easy to run on a wider range of machines
  presets: [
    [
      "@babel/preset-env",
      {
        targets: {
          // target an older version where I know there is no ESM support
          node: "10"
        }
      }
    ]
  ],
  // this was in the docs too - I'm not sure if  I need it TBH
  sourceType: "module"
}

I have a bunch of code using import/export, and async/await in a directory, that I wanted to transpile and put into another directory, lib.

Here's the command I am using:

npx babel src --out-dir lib

My package.json file online too, and there's nothing too esoteric there. I've tried to follow the documentation faithfully.

I would expect to see changes in the code to replace the import/export calls with requires in the lib, but no joy.

What am I doing wrong here? I worked on a related project 6-7 months ago, where I am using babel like this and it does make the changes for me.

You can see the branch with the problem code on github, with the package.json, and here's the source code for other project mentioned where it is working.

Please be gentle, fellow SO commenters - I'm trying my best, I really am.


Solution

  • It looks like you're using "babel-cli": "^6.26.0" instead of "@babel/cli": "^7.11.6" that should fix it.