Home > database >  How to support ECMa or Common js version for my npm package
How to support ECMa or Common js version for my npm package

Time:01-21

I have already tested my npm package after Rollup.js bundle and i got two files. index.mjs and index.cjs. And i want somehow give people permission to choise between them. I dont think creating two package only for support both of them is good idea or publish 1.0.0 for ecma version and 1.5.0 for cmjs version neither is good idea. Is there a way to make fully support? Thank in advance.

CodePudding user response:

Unfortunately, I don't think there is a way to make a single package that fully supports both the ECMAScript and CommonJS modules. The two module formats are incompatible... so you would have to publish two separate packages.

But you might consider using ES6 transpilers such as Babel or TypeScript in order to convert your code into either format depending on the user's needs. This might require some additional setup on the user's side but could be quite an effective solution if they only need one of the formats and don't want to download both packages separately.

EDIT:

Babel is a tool that basically allows you to convert your code between different formats, so you can use it to transpile your package from one format (ECMAScript) into another (CommonJS). Users would first need to install both the core Babel package and any additional plugins/presets needed. You can use NPM or Yarn.

NPM installation:

npm install @babel/core @babel/preset-env --save-dev

Yarn: yarn add @babel/core @babel/preset-env --dev

Check out Babel's official documentation here: https://babeljs.io/docs/en/. They have pretty detailed instructions on how to download and use Babel for various use cases, including converting from one module system format to another.

  • Related