I would like to write in TypeScript a npm package and I want that the user will be able to use it in both Angular and node environments.
I saw that this question was asked many times, like here or here, but it's not exactly what I want. I found a lot of other responses, like this excellent article, but I still have a problem, and I don't know why. I try to solve it since two days and I think that I will soon become crazy.
Example :
My awesome package :
index.ts
import { hello } from './file-to-import';
export function sayHello() {
hello();
}
file-to-import.ts
export function hello() {
console.log('Hello');
}
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"target": "es5",
"declaration": true,
// ....
}
}
Now I compile the library with tsc
, publish it and try to use it in Angular for the frontend and in NodeJs for the backend.
- First try with the combination
commonjs/es5
:
All is ok for the backend, but in the frontend, Angular gives a warning : ... depends on 'my-awesome-module'. CommonJS or AMD dependencies can cause optimization bailouts.
. I could ask the user to solve this problem by adding my module to allowedCommonJsDependencies
option in angular.json
, but I think that's not a good idea.
- Second try with the combination
es6/es5
oresnext/es5
:
Now, all is ok for Angular, but nodejs says in the backend : SyntaxError: Cannot use import statement outside a module
.
- Third try with the combination
umd/es5
:
All is perfect for NodeJs, but Angular throws the same error than in the first try and adds other warnings : Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
.
I think that it's possible to transpile the module two times, one with a tsconfig
with esnext/es5
and the other with commonjs/es5
, but I don't know how to do that and if it's a good idea.
Any help will be welcome !