3

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';
FZs
  • 16,581
  • 13
  • 41
  • 50
Ajay Agrawal
  • 43
  • 2
  • 8
  • There is no such thing as "ES5 style". Those are nodejs modules. – Jared Smith Dec 05 '21 at 21:35
  • https://nodejs.org/api/packages.html has all the info you need. Also https://2ality.com/2019/10/hybrid-npm-packages.html – Bergi Dec 05 '21 at 22:24
  • possible duplicate of https://stackoverflow.com/questions/63121593/how-can-i-publish-an-npm-module-with-both-commonjs-and-es6-versions – Bergi Dec 05 '21 at 22:28

1 Answers1

3

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.

fast-reflexes
  • 4,891
  • 4
  • 31
  • 44