Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid "Module not found: Error: Can't resolve 'tslib'"-error when referencing an external typescript file?

The question

I have a client/server application, where the client is an angular-app. The server does provide a couple of typescript-definitions for the API it provides. These definitions are loaded from a project-external folder. So far this worked fine, however now I am upgrading from Angular 7 to Angular 8 (and with that also upgrading Typescript from Version 3.1 to 3.5) and when trying to use a non-static enum from the definitions, this now produces this error:

Module not found: Error: Can't resolve 'tslib' in '/path/to/server/definitions'

When the api.ts-file is located within the client-dir, then everything works just fine.

Why is this happening and what I can I do about it?

Creating a minimal reproducible example

Here is a quick script to create a minimal example to reproduce:

mkdir project
cd project
ng new client --minimal=true --skipGit=true --routing=false --style=css
mkdir server
echo 'export enum ApiSample { X = "X" }' > server/api.ts
sed -i 's/"compilerOptions": {/"compilerOptions": {"paths":{"api":["..\/server\/api"]},/' client/tsconfig.json
sed -i -e "1iimport { ApiSample } from 'api';" -e "s/title = 'client';/title = 'client' + ApiSample.X;/" client/src/app/app.component.ts
cd client
npm start

Or, alternatively, to create an example manually:

  1. Create a new angular project
  2. Create somewhere in the filesystem a file "api.ts" with the content export enum ApiSample { X = "X" }
  3. In the "tsconfig.json" Add {"paths":{"api":["/path/to/server/api"]} to the compilerOptions
  4. Access the ApiSample.X from any file of the angular project
  5. Run npm start

Findings so far

  • The migrator added "importHelpers": true in tsconfig.json. That is why it worked before and is not working anymore now. Specifying "importHelpers": false in tsconfig.json fixes the issue, but of course this option is there for a reason, so that is no final solution
  • Explicitly specifying "tslib": ["node_modules/tslib"] fixes the problem. This may be a final solution although it would be interesting to know what is exactly happening and where this is documented.
like image 208
yankee Avatar asked Oct 06 '19 17:10

yankee


1 Answers

Angular 8&9

So for Angular 8 and 9 it seem that adding "tslib": ["node_modules/tslib"] to compilerOptions/paths in the tsconfig.json does solve the problem.

Angular 10

In Angular 10 the problem disappeared altogether, no workaround is needed anymore.

like image 141
yankee Avatar answered Nov 15 '22 05:11

yankee