Home > Enterprise >  How to allow both import ES5 and ES6 to my npm package?
How to allow both import ES5 and ES6 to my npm package?

Time:12-07

I am new to npmjs package publishing and recently published my 1st package successfully. But since it's written in ES5 style. It is accessed only via "require"

const smiley = require('smiley-id');

What should be done to make it accessible via import statement also? like this

import smiley from 'smiley-id'; 

or/and

import { smileyId } from 'smiley-id';

CodePudding user response:

require is part of the CommonJS module system (also known as cjs modules) whereas import and export are used in es2015 module system (also known as JavaScript modules, es6 modules or esm modules).

You can use import for both cjs and esm modules, but you cannot use require for esm modules. This means that in an esm module (or source file which you will compile with Typescript tsc or Babel or bundle with Webpack) you can already import your package, as it is, with import. However, you cannot use named imports. Instead you have to destructure the imported item afterwards.

If you want to distribute it as an esm package, this is also possible and it comes with some advantages, out of which the most important is related to tree-shaking. To distribute it as an esm module, you tell your build tool to output esm modules. This is different for different tools. Fortsc for example you specify --module es6 (there are multiple targets that output esm modules). For Webpack, Babel and Rollup, the procedure is different.

  • Related