How to publish a module written in ES6 to NPM?

前端 未结 11 657
自闭症患者
自闭症患者 2020-11-29 15:22

I was about to publish a module to NPM, when I thought about rewriting it in ES6, to both future-proof it, and learn ES6. I\'ve used Babel to transpile to ES5, and run tests

11条回答
  •  半阙折子戏
    2020-11-29 16:06

    Node.js 13.2.0+ supports ESM without the experimental flag and there're a few options to publish hybrid (ESM and CommonJS) NPM packages (depending on the level of backward compatibility needed): https://2ality.com/2019/10/hybrid-npm-packages.html

    I recommend going the full backward compatibility way to make the usage of your package easier. This could look as follows:

    The hybrid package has the following files:

    mypkg/
      package.json
      esm/
        entry.js
      commonjs/
        package.json
        entry.js
    

    mypkg/package.json

    {
      "type": "module",
      "main": "./commonjs/entry.js",
      "exports": {
        "./esm": "./esm/entry.js"
      },
      "module": "./esm/entry.js",
      ···
    }
    
    mypkg/commonjs/package.json
    
    {
      "type": "commonjs"
    }
    

    Importing from CommonJS:

    const {x} = require('mypkg');
    

    Importing from ESM:

    import {x} from 'mypkg/esm';
    

    We did an investigation into ESM support in 05.2019 and found that a lot of libraries were lacking support (hence the recommendation for backward compatibility):

    • esm package's support doesn't align with Node's which causes issues
      • "Builtin require cannot sideload .mjs files." https://github.com/standard-things/esm#loading, https://github.com/standard-things/esm/issues/498#issuecomment-403496745
      • "The .mjs file extension should not be the thing developers reach for if they want interop or ease of use. It's available since it's in --experimental-modules but since it's not fully baked I can't commit to any enhancements to it." https://github.com/standard-things/esm/issues/498#issuecomment-403655466
    • mocha doesn't have native support for .mjs files
      • Update 2020-01-13: Mocha released experimental support in mocha@7.0.0-esm1
    • Many high-profile projects had issues with .mjs files:
      • create-react-app
      • react-apollo
      • graphql-js
      • inferno

提交回复
热议问题