DEV Community

loading...

What is your output target for publishing NPM modules?

JavaScript Joel
Cofounded Host Collective (DiscountASP.net). Cofounded Player Axis (Social Gaming). Computer Scientist and Technology Evangelist with 20+ years of experience with JavaScript!
・2 min read

When using Webpack with babel-loader, imported NPM Modules are not babeled. This is due to a common exclude rule.

/*
 * webpack.config.js
 */
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$|\.jsx$/,
        use: "babel-loader",
        exclude: /node_modules/,
      }
    ]
  }
};

So the imported module must already be in a mostly-compatible state. This can mean different things based on your web application.

For example, if your web application requires support for IE11, the published module must also support IE11.

You could ensure your module supports IE11, but what if a web app requires supporting further environments?

Supporting environments back to the dawn of civilization will also bloat your NPM Module, making it slower for all non-IE11 apps.

The other option is to have the user of your module also Babel it, if they need additional support.

I had to do this for strict-uri-encode:

  exclude: /node_modules\/(?!(strict-uri-encode)\/).*/

This also doesn't seem to be practical. Especially if an NPM Module depends on your NPM Module, that module would have to decide to either Babel your module to match it's output target or to also bubble this decision up to the user of their NPM Module.

You could also make a "best effort" approach. Which would be to Babel your code to a reasonably supported target, and then let the user know if they want more, that's on them.

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "8.10"
        }
      }
    ]
  ]
}

in README.md

# Module Target

This module targets ES6 and specifically node 8.10. If you need to target other environments, you are responsible for Babeling this module.

I have also seen @pika/pack, which I haven't played with yet, but it's worth a mention.

I have also seen esnext, along with main added to package.json. Still researching this.

Worth a read: Delivering untranspiled source code via npm - 2ality

I'm currently going with this "best effort" approach.

What do you do in your published NPM projects?

Discussion (0)