BalbelJS

BalbelJS to transpile your new syntax code to work with older format. It basically recompile your new syntax to the old one which support by other browser.

Use BalbelJS to transpile CommonJS (CJS) to ECMAScript Module (ESM)

We can also use it to transpile from CommonJS (CJS) to ECMAScript Module (ESM) and vice versa using babel plugins. For example:

// babel.config.json
{  
  "presets": [  
    [  
      "@babel/preset-env",  
      {  
        "targets": {  
          "edge": "17",  
          "firefox": "60",  
          "chrome": "67",  
          "safari": "11.1"  
        },  
        "useBuiltIns": "usage",  
        "corejs": "3.6.5",  
        "modules": false // put false to transform to browser support
      }  
    ]  ],  
  "plugins": ["transform-commonjs"],  // plugin to transform Commonjs to ESM
  "ignore": [  
    "build/**/*",  
    "node_modules/**/*"  
  ]}
}
<!-- index.html -->
<html>  
    <body>Example babeljs</body>  
    <script type="module" src="build/index.js"></script>  
</html>
// Either syntax should work

// import Logger from './src/logger.js';  
const Logger = require("./src/logger.js")  
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];  
Logger.log(data);
// src/logger.js
class Logger {  
    log(content) {  
        console.log(content)  
    }  
}  
  
  
module.exports = new Logger()

Note: in here for logger.js we're still using CommonJS (CJS) syntax.

// package.json
{  
  "name": "client",  
  "version": "1.0.0",  
  "dependencies": {  
  },  
  "scripts": {  
    "compile": "npx babel . --out-dir build --delete-dir-on-start"  
  },  
  "devDependencies": {  
    "babel-plugin-transform-commonjs": "^1.1.6",
    "@babel/cli": "^7.23.0",  
    "@babel/core": "^7.23.2",  
    "@babel/preset-env": "^7.23.2",  
    "core-js": "^3.33.1"
  }  
}