Tsconfig paths не работает

пути tsconfig не работают

Я пытаюсь сделать что-то очень похожее на пример jquery path в документации, но TS продолжает бросать TS2307 (веб-пакет компилируется нормально):

Изменение baseUrl на «.» и обновление includes и paths не имеет значения ( @client продолжает работать, а @suir не работает).

Изменение «@suir» на «@suir/» или «@suir/*» (и добавление /* к его значению) также не имеет значения.

Причина, по которой я делаю это, состоит в том, чтобы упростить свой импорт (я указываю их явно вместо того, чтобы извлекать именованные экспортные данные из пакета, чтобы уменьшить размер пакета моего поставщика — экономия около 1 МБ):

2 ответа

Я понятия не имею, почему это сейчас работает в одиннадцатый раз, который я пробовал (но не первые 10), но /* , похоже, является секретным соусом, а пример в документации, очевидно, указывает на конкретный файл (при этом расширение файла опускается).

Это может кому-то помочь — если вы используете tsc или инструмент для компиляции кода TS в отдельную папку, например dist , регистр tsconfig-paths НЕ работает коробка. У меня есть tsconfig.json вот так:

Вы можете видеть, что такой путь, как shared/someFolder/someScript , будет правильно разрешен в папку shared в моем проекте, что значительно облегчит загрузку, чем множество относительных путей ../../../../ .

Однако это вызывало ошибку:

Я немного покопался и обнаружил, что массив tryPaths , созданный tsconfig-paths, имеет абсолютные URL-адреса относительно базы project / cwd, а не папки сборки dist .

Источник

Visual Studio Code can’t resolve angular’s tsconfig paths

I’m trying to import some services using barrels and tsconfigs paths options but I can’t get angular and vscode to get along.

If it works for one it doesn’t for the other and viceversa.

My situation seems to be pretty simple:

  • in src/app/services I have a service which is exported in a index.ts
  • my src/tsconfig.app.json is just this:

and my angular app compiles with no issues, but vscode keep giving me errors every time I try to import my service from ‘services’ giving me [ts] Cannot find module ‘services’.

I’m using typescript 3.1.6 and in vscode settings I have «typescript.tsdk»: «C:/Users/myuser/AppData/Roaming/npm/node_modules/typescript/lib» (I also tried to leave the default setting, no changes)

Читайте также:  Не работает прикуриватель атего

edit:

if I specify paths in ./tsconfig.json starting from src , vscode is happy but angular is not.

if I specify paths in both tsconfig.json and src/tsconfig.app.json , both vscode and angular are happy, but it seems a too stupid workaround to me.

6 Answers 6

I figured it out, even if I’m keep thinking that is all absurd.

VsCode automatically looks for a tsconfig.json file and it doesn’t care about tsconfig.app.json , so paths needs to be specified in tsconfig.json .

At the same time, the angular-cli scaffolding specify a baseUrl parameter in tsconfig.app.json which overrides the upper one.

The solution is to delete baseUrl parameter in the tsconfig.app.json or edit its value to «../»

(As a personal remark, given that vscode is largely used to build angular solutions, I think that there’s something that should be revisited in the angular-cli scaffolding or in how vscode looks for tsconfig files)

Источник

How to use paths in tsconfig.json?

I was reading about path-mapping in tsconfig.json and I wanted to use it to avoid using the following ugly paths:

The project organization is a bit weird because we have a mono-repository that contains projects and libraries. The projects are grouped by company and by browser / server / universal.

How can I configure the paths in tsconfig.json so instead of:

Will something else be required in the webpack config? or is the tsconfig.json enough?

13 Answers 13

This can be set up on your tsconfig.json file, as it is a TS feature.

You can do like this:

Have in mind that the path where you want to refer to, it takes your baseUrl as the base of the route you are pointing to and it’s mandatory as described on the doc.

The character ‘@’ is not mandatory.

After you set it up on that way, you can easily use it like this:

the only thing you might notice is that the intellisense does not work in the current latest version, so I would suggest to follow an index convention for importing/exporting files.

You can use combination of baseUrl and paths docs.

Assuming root is on the topmost src dir(and I read your image properly) use

For webpack you might also need to add module resolution. For webpack2 this could look like

Check this similar solutions with asterisk

This works for me:

This loads all paths in tsconfig.json. A sample tsconfig.json:

Make sure you have both baseUrl and paths for this to work

And then you can import like :

If you are using paths, you will need to change back absolute paths to relative paths for it to work after compiling typescript into plain javascript using tsc .

Most popular solution for this has been tsconfig-paths so far.

I’ve tried it, but it did not work for me for my complicated setup. Also, it resolves paths in run-time, meaning overhead in terms of your package size and resolve performance.

So, I wrote a solution myself, tscpaths.

I’d say it’s better overall because it replaces paths at compile-time. It means there is no runtime dependency or any performance overhead. It’s pretty simple to use. You just need to add a line to your build scripts in package.json .

Читайте также:  Как настроить dpi a4tech bloody

The project is pretty young, so there could be some issues if your setup is very complicated. It works flawlessly for my setup, though my setup is fairly complex.

Источник

Cannot find module that is defined in tsconfig `paths`

I am trying to setup aliases for my mock server. Whenever I try to compile ts files, it returns error that it couldn’t find proper modules even though those are defined in tsconfig,json -> paths

Here is my tsconfig.json

Error: Error: Cannot find module ‘@project/server/data/accounts/accountsList’

10 Answers 10

I faced the same issue. I tried many things and now i got a solution which works for me. I have an app and a library in my angular project. I want to use a library alias in my app.

I have following structure:

In the tsconfig.json file in the root folder I have following paths defined:

There I access an index.ts file where I define the things I want to export. In my case the index.ts file has the following entry:

Now I can access the LibService in components of the app with the help of the alias:

It is important to mention that this soloution don’t work if I add this entry to the tsconfig.app.json file. I think the IDE (in my case WebStorm) searches for aliases in the tsconfig.json file which is close to the root folder. So I extend the tsconfig.json in my tsconfig.app.json

Maybe you have to restart you IDE to remove the red underline of the import line.

Источник

tsconfig-paths doesn’t work with node (works with ts-node) #61

Comments

darkbasic commented Oct 23, 2018

Repro: https://github.com/darkbasic/guild-review
yarn && yarn workspace server build && cd server && node -r tsconfig-paths/register dist/index.js

The text was updated successfully, but these errors were encountered:

kel-sakal-biyik commented Oct 25, 2018

I have the same problem. I also tried to put tsconfig.json file under dist but didn’t help.

dotansimha commented Oct 26, 2018

As a workaround, you can do node -r ts-node/register -r tsconfig-paths/register dist/index.js .
@kel-sakal-biyik @darkbasic

kel-sakal-biyik commented Oct 26, 2018

@darkbasic I moved a tsconfig.json file under dist folder with only path configuration and run the index.js under dist folder. By doing so it read the tsconfig file under the dist folder and it worked. You can give it a try, it might help you too.

chanlito commented Oct 29, 2018

Yep just tried it not working with node, and @dotansimha solution I believe it’s not optimal for production environment.

jelling commented Oct 30, 2018

@bushybuffalo reported a fix here. I couldn’t get it to work with my project but our configuration is more complicated than the example. I went with @kel-sakal-biyik’s solution for now.

chanlito commented Dec 2, 2018

So I end up using the following:

«start»: «node -r ts-node/register/transpile-only -r tsconfig-paths/register dist/main.js»

Hope it doesn’t have any negative impact.

joseluisq commented Jan 24, 2019 •

So I end up using the following:

«start»: «node -r ts-node/register/transpile-only -r tsconfig-paths/register dist/main.js»

Читайте также:  Не работает плеймаркет самсунг

Hope it doesn’t have any negative impact.

Right, but the particularity about this temporary workaround is that I need to move ts-node to dependencies section. For example to deploy my app into a Docker container.

Ideal solution (again) would be just run the transpiled code:

sandangel commented Mar 20, 2019

May I ask for an update on this issue?

mehtamanan commented Jul 21, 2019

joseluisq commented Jul 22, 2019 •

I have created a persistent Typescript paths replacer for those wants to replace TS path aliases directly. No runtime replace.

jeffminsungkim commented Oct 16, 2019

@chanlito Tried your solution, but I’m having the following error message.

EntityMetadataNotFound: No metadata for «SomeEntityClass» was found.

chanlito commented Oct 16, 2019

@jeffminsungkim are you using reflect-metadata ? did you import or require it?

keesvanlierop commented Oct 16, 2019

With node
node -r tsconfig-paths/register main.js

So this bit from the README should be removed to avoid confusion

jeffminsungkim commented Oct 17, 2019 •

@chanlito I believe that the Nest.js framework uses reflect-metadata . So my answer is yes.

mkalam-alami commented Mar 15, 2020 •

I managed to make it work by using the TS_NODE_PROJECT env variable to point to a tweaked tsconfig file. In practice this means:

Launch script

tsconfig.prod.json

For some reason I could not override the compilerOptions.paths to rewrite them from the new baseUrl , but this particular setup seems OK.

ejhayes commented Apr 3, 2020

Running into this issue as well. Seems like the common solution requires changing the baseUrl value so it’ll work in prod. See #114

SkaceKamen commented May 3, 2020 •

So the issue is, that the baseUrl will be resolved relative to tsconfig.json in root of your project, but in reality, it should point to your dist folder (or wherever your compiled files are). This package is working fine and it’s not actually a bug, but I think adding something like TS_PATHS_ROOT environment variable, that would allow people to override the root of baseUrl would be much appreciated (actually there’s already a PR for that — #114)

So the node.js is trying to load your actual typescript source files. Using the -r ts-node/register/transpile-only workaround basically means you will compile your typescript files twice because you’ll be importing the typescript files (that use the paths) not the compiled javascript. It’s almost the same as running ts-node on your uncompiled index file.

One possible solution is to copy tsconfig.json to your dist path and set the current working directory (CWD) to said dist path when running the file. You have to set the CWD to dist because the tsconfig.json in CWD has the highest priority.

Another possible solution (and probably much cleaner) is to use mentioned https://github.com/ilearnio/module-alias, just keep in mind you have to point to your dist folder.

Example

then you can use vscode to debug run with following config:

Источник

Оцените статью