1

First of all, I'm NOT talking about "allowedCommonJsDependencies". That's just a matter of suppressing warnings. What I want to do is author an npm package, to be used by Angular projects as well as non-Angular projects, so that there will be no warnings which have to be suppressed.

My package already contains ESM-style modules, as well as CommonJS (and even minified UMD). There are both ES6 (ES2015) and ES5 code versions available. Here's the start of my package.json:

{
  "name": "@tubular/util",
  "version": "3.3.0",
  "description": "Miscellaneous utility functions",
  "browser-es5": "dist/web5/index.js",
  "browser-es6": "dist/web/index.js",
  "main": "dist/es5/index.js",
  "module": "dist/index.js",
  "es2015": "dist/es6/index.js",
  "esm2015": "dist/index.js",
  "typings": "dist/index",
  "sideEffects": false,

The code at dist/index.js looks like this:

export * from './browser-graphics-util';
export * from './browser-util';
export * from './misc-util';
export * from './string-util';

...and all the code that is exported above is written in the ESM style, using import, not require.

So why is Angular complaining about the CommonJS code, instead of happily grabbing the ESM code and using that instead, without any need for warnings?

Full source code here: https://github.com/kshetline/tubular_util

kshetline
  • 12,547
  • 4
  • 37
  • 73
  • https://stackoverflow.com/questions/62592903/upgrading-to-angular-10-fix-commonjs-or-amd-dependencies-can-cause-optimizatio – Piyush Jain Feb 02 '21 at 03:07
  • @Piyush Jain, sorry, what you linked to is about *using* npm modules, as they are, that are CommonJS, not about *creating those npm modules* so that they can be consumed as ESM packages. – kshetline Feb 02 '21 at 03:56

1 Answers1

0

It's not incredibly well documented, but after I posted an issue on Github, I finally learned how Angular determines which code inside an npm package to use. Angular checks this hierarchy:

  • es2015
  • browser
  • module
  • main

The 'esm2015' property isn't even checked, and that's exactly where I'd put ESM-style code. I wrongly expected that 'es2015', without the 'm', shouldn't be ESM code.

Wrong!

My new package.json looks like this, with all of the code directories as they were before:

{
  "name": "@tubular/util",
  "version": "3.3.1",
  "description": "Miscellaneous utility functions",
  "browser": "dist/web/index.js",
  "browser-es5": "dist/web5/index.js",
  "main": "dist/es6/index.js",
  "main-es5": "dist/es5/index.js",
  "module": "dist/index.js",
  "es2015": "dist/index.js",
  "typings": "dist/index",
  "sideEffects": false,

With this, Angular can optimize and tree-shake to its heart's content.

kshetline
  • 12,547
  • 4
  • 37
  • 73