gpt4 book ai didi

Why are these tsconfig paths not working?(为什么这些tsconfig路径不起作用?)

转载 作者:bug小助手 更新时间:2023-10-25 20:04:59 24 4
gpt4 key购买 nike



I'm trying to do something very similar to the jquery path example in the documentation, but TS keeps throwing TS2307 (webpack compiles fine):

我正在尝试做一些与文档中的jQuery路径示例非常类似的事情,但TS一直抛出TS2307(webpack编译得很好):



"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@client": [
"client",
],
"@suir": [
"../node_modules/semantic-ui-react/dist/commonjs", // not working
],
},
// …
},
"include": [
"*.d.ts",
"client/**/*",
"../node_modules/semantic-ui-react", // is this necessary?
],


Changing baseUrl to "." and updating includes and paths makes no difference (@client continues to work and @suir continues to not work).

将baseUrl更改为“。“并且更新includes和paths没有区别(@client继续工作而@suir继续不工作)。



Changing "@suir" to "@suir/" or "@suir/*" (and appending /* to its value) also makes no difference.

将“@Suir”更改为“@Suir/”或“@Suir/*”(并在其值后附加/*)也没有区别。






The reason I'm doing this is to simplify my imports (I'm specifying them explicitly instead of pulling named exports from the bundle in order to reduce my vendor bundle size—saves about 1 MB):

我这样做的原因是为了简化我的导入(我显式地指定它们,而不是从捆绑包中提取命名的导出,以减小我的供应商捆绑包大小-节省大约1 MB):



import Button from 'semantic-ui-react/dist/commonjs/elements/Button'; // works

import Button from '@suir/elements/Button'; // not found

更多回答

Just wanted to add to this. For me, paths stop working when i use the files property in tsconfig.json. Any solution for this?

只是想补充一下这个。对我来说,当我使用tsconfig.json中的FILES属性时,路径停止工作。对此有什么解决方案吗?

优秀答案推荐

I have no idea why this is now working on the eleventh time I tried (yet didn't the first 10), but the /* seems to be the secret sauce, and the example in the docs is apparently pointing to a specific file (and the file extension is omitted).

我不知道为什么这在我第11次尝试(但前10次没有)时起作用,但是/*似乎是秘密武器,并且文档中的示例显然指向特定的文件(并且省略了文件扩展名)。


{
"compilerOptions": {
"baseUrl": "./src", // setting a value for baseUrl is required
"moduleResolution": "node", // was not set before, but is the default
"paths": {
"@client/*": [
"client/*",
],
"@suir/*": [ // notice the `/*` at the end
"../node_modules/semantic-ui-react/dist/commonjs/*", // notice the `/*`
],
},
// …
},
"include": [
"./src/client/**/*",
],
}


As mentioned in the comments by Emily Zhai, this can sometimes just require a language server restart.

正如艾米丽·翟伟在评论中提到的,这有时只需要重新启动语言服务器。


In VSCode, you can press Cmd/Ctrl + Shift + P and search for Typescript: Restart TS Server.

在VSCode中,您可以按Cmd/Ctrl+Shift+P并搜索TypeScrip:重新启动TS服务器。


After restarting, everything started working for me.

重新启动后,一切都开始为我工作。



I did also struggle with .tsconfig not recognizing my aliases (while in another project that supposed to have the save config it worked perfectly).

我也确实在为.tsconfig无法识别我的别名而挣扎(而在另一个应该有保存配置的项目中,它工作得很好)。


As it turned out, it was a rookie mistake: I put the paths prop to the end of the JSON object, but it has to be a nested property of the compilerOptions part:

事实证明,这是一个新手错误:我将路径道具放在JSON对象的末尾,但它必须是编译器选项部分的嵌套属性:


// This does't work ❌
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
//...
"baseUrl": ".",
},
"include": ["next-env.d.ts", "twin.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"],
"paths": {
"@components/*": ["components/*"],
"@lib/*": ["lib/*"]
}
}

// This should work ✅
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
//...
"baseUrl": ".",
"paths": {
"@components/*": ["components/*"],
"@lib/*": ["lib/*"]
}
},
"include": ["next-env.d.ts", "twin.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"],
}


Out of the box, it doesn't work with tsc or ts-node.
But with some packages (tsc-alias & module-alias), it works.
No babel or webpack setup are required.

开箱即用,它不适用于TSC或TS-NODE。但对于某些包(tsc-alias和模块-alias),它是有效的。不需要设置巴别塔或webpack。


// tsconfig.json

{
"compilerOptions": {
...
"baseUrl": "./src",
"paths": {
"@common/*": ["common/*"],
"@services/*": ["services/*"],
},
...
},
}

Working with TSC


Add tsc-alias (https://www.npmjs.com/package/tsc-alias) as dev dependency

添加tsc别名(https://www.npmjs.com/package/tsc-alias)作为开发依赖项


yarn add --dev tsc-alias

And add it to your build command

并将其添加到构建命令中


"build": "tsc && tsc-alias",

Working with TS-NODE


Add module-alias (https://www.npmjs.com/package/module-alias) dependency

添加模块别名(https://www.npmjs.com/package/module-alias)依赖项


yarn add module-alias

Create a file referencing all aliases

创建引用所有别名的文件


// src/paths.ts

import 'module-alias/register';
import { addAliases } from 'module-alias';

addAliases({
'@common': `${__dirname}/common`,
'@services': `${__dirname}/services`,
});

And import it in your entry script as first import

并将其作为第一次导入导入到入门脚本中


// src/server.ts

import './paths';
import express, { Request, Response, NextFunction } from 'express';
...

const app = express();
...
app.listen(port, onListen(port));


This might help someone - if you use tsc or a tool to compile your TS code to a separate folder such as dist, tsconfig-paths register does NOT work out the box. I have a tsconfig.json like this:

这可能会对某些人有所帮助--如果您使用TSC或工具将您的TS代码编译到一个单独的文件夹,如dist,tsconfig--路径寄存器不能正常工作。我有一个如下所示的tsfig.json:



{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": ["dom", "esnext"],
"baseUrl": ".",
"jsx": "react",
"removeComments": true,
"sourceMap": true,
"outDir": "dist"
"rootDir": ".",
"paths": {
"shared/*": ["./shared/*"],
}
},
"include": ["./client/**/*", "./server/**/*"]
}


You can see that a path such as shared/someFolder/someScript will resolve correctly to the shared folder in my project, which is a load cleaner than lots of relative ../../../../ paths.

您可以看到,诸如Shared/ome Fold/omeScrip之类的路径将正确解析为我的项目中的共享文件夹,这比许多相对.././路径更能清理负载。



However, this was throwing me the error:

然而,这给了我一个错误:



➜  game git:(game-dev) ✗ node --inspect -r tsconfig-paths/register dist/server/runProd.js
Debugger listening on ws://127.0.0.1:9229/f69956aa-d8d6-4f39-8be1-9c3e8383d4be
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
internal/modules/cjs/loader.js:584
throw err;
^

Error: Cannot find module 'shared/types/UserTypes'


I did a bit of digging and found that the tryPaths array produced by tsconfig-paths has absolute URLs relative to the project/cwd base, rather than the build dist folder.

我做了一些调查,发现tsconfig-路径生成的tryPath数组拥有相对于project/cwd基目录的绝对URL,而不是相对于Build dist文件夹的。



inspect screengrab



This seems obvious in retrospect. There doesn't seem to be an obvious way to handle this with the library, so I have solved this by copying the tsconfig.json into the dist folder and running node -r tsconfig-paths/register main.js.

回想起来,这似乎是显而易见的。似乎没有一种明显的方法来处理这个库,所以我已经解决了这个问题,方法是将tsfig.json复制到dist文件夹中,然后运行node-r tsconfig-路径/Register main.js。



After some trial and error, I got to know that, it works differently than we think.

经过一些试验和错误,我知道,它的工作方式与我们想象的不同。


//tsconfig.json
"baseUrl": ".",
"paths": {
"@components/": ["src/components/"],
}

//SomeCompomonent.tsx
import { Button } from "@components/" // will work
import Button from "@components/Button" // will not work

to make the second import line work you need to put *

要使第二条进口线正常工作,您需要将*


//tsconfig.json
"baseUrl": ".",
"paths": {
"@components/*": ["src/components/*"],
}

//SomeCompomonent.tsx
import { Button } from "@components/" // will not work
import Button from "@components/Button" // will work

To make both work

要让这两种方法都发挥作用


//tsconfig.json
"baseUrl": ".",
"paths": {
"@components/": ["src/components/"],
"@components/*": ["src/components/*"],
}

//SomeCompomonent.tsx
import { Button } from "@components/" // will work
import Button from "@components/Button" // will work


Like, pkestikar said, tsconfig-paths-webpack-plugin can help with that. Save it on devDependencies with yarn add --dev tsconfig-paths-webpack-plugin , add the following configuration on next.config.js

就像pkstikar所说的那样,tsconfig-路径-webpack-插件可以帮助实现这一点。将其保存在DevDependors上,并使用YAR Add--dev tsconfig-paths-webpack-plugin,在next.config.js上添加以下配置


const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')

module.exports = {
resolve: {
plugins: [new TsconfigPathsPlugin({ configFile: "./tsconfig.json" })]
}
}

My paths started to work with that. Here's my tsconfig.json

我的人生道路就是这样开始的。这是我的tsfig.json


"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@components/*": ["components/*"]
},
}

And here is the import of a component.

下面是一个组件的导入。


import { Button } from '@/components/Button/Button'

从‘@/组件/按钮/按钮’导入{Button}


It works with just import { Button } from 'components/Button/Button' as well.

它也适用于从‘Components/Button/Button’导入{Button}。



If you are using Vite, you should install vite-tsconfig-paths.

如果您使用的是vite,则应安装vite-tsconfig-路径。


npm i vite-tsconfig-paths --save-dev

Then, inject vite-tsconfig-paths using the vite.config.ts module

然后,使用vite.fig.ts模块注入vite-tsconfig-路径


import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
plugins: [tsconfigPaths()],
})

You may need to restart Vite and/or your TS server after making these changes.

进行这些更改后,您可能需要重新启动VITE和/或您的TS服务器。



If someone still has this issue even after doing everything mentioned. Try close down VS code and reopen again, that worked for me 2 hours after looking around..

如果有人在做了上面提到的所有事情后仍然有这个问题。试着关闭VS代码,然后重新打开,在环顾了两个小时后,这对我来说很管用。



Even if the base url is set check if it's on the default value "./"
then should be changed to "src", only that way worked for me.

即使设置了基本URL,也要检查它是否在默认值“。“那么应该改为“src”,只有这种方式为我工作。



If you are using Webpack with ts-loader and it's still not working after trying all of the answers above, you might need to use a plugin in the resolve section of your Webpack config file - tsconfig-paths-webpack-plugin; so it follows the paths you've put in in your tsconfig.json file while compiling.

如果你使用的是带有ts-Loader的webpack,在尝试了上面所有的答案之后,它仍然不起作用,你可能需要在webpack配置文件的Resolve部分使用一个插件-tsconfig-路径-webpack-plugin;这样它就会遵循你在编译时在tsfig.json文件中输入的路径。


Source - https://github.com/TypeStrong/ts-loader#baseurl--paths-module-resolution

来源-https://github.com/TypeStrong/ts-loader#baseurl--paths-module-resolution



While trying to make tsconfig work, the following command proved very helpful:

在尝试使tsconfig正常工作时,事实证明以下命令非常有用:




npx tsc --showConfig




This will output some json with the files field showing the actual recognized files by your configuration.

这将输出一些带有FILES字段的json,显示您的配置实际识别的文件。



Try add in tsConfig.json the follow property inside CompileOptions:

尝试在CompileOptions内的以下属性中添加tsConfig.js:


"baseUrl": "."

“BasUrl”:“。”


In my case working.

在我的情况下是工作的。



I had to use babel to compile the code

我不得不用巴别塔来编译代码


npm i -D @babel/cli @babel/core @babel/node @babel/preset-env @babel/preset-typescript babel-plugin-module-resolver

Then on the build command

然后在Build命令上


"build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files --no-copy-ignored"

And the babel.config.js

和Babel.config.js


module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current'
}
}
],
'@babel/preset-typescript'
],
plugins: [
['module-resolver', {
alias: {
'@config': './src/config',
'@modules': './src/modules',
'@shared': './src/shared'
}
}]
],
ignore: [
'**/*.spec.ts'
]

}

}



In my case the issue was that I was adding path to the wrong file. If you are working on a big project where you are not sure of it's configurations, chances are that the config file be extended by other files. In my project there was another file called tsconfig.app.json, notice the extend attribute in the very first row:

在我的例子中,问题是我将路径添加到了错误的文件。如果您正在处理一个不确定其配置的大型项目,则配置文件很可能会被其他文件扩展。在我的项目中有另一个名为tsconfig.app.json的文件,请注意第一行中的EXTEND属性:


{
"extends": "../tsconfig.json",
"compilerOptions": {
"paths": {
"@angular/*": [
"../node_modules/@angular/*",
],
"@app/*": ["app/*"]
}
}


I will recommend, do not change tsconfig.json rather create tconfig.app.json and add following content
If already exists then simply add paths, you can reuse your shortPath

我会建议,不要更改tsconfig.json,而是创建tfig.app.json并添加以下内容如果已经存在,则只需添加路径,即可重复使用您的短路径


Note: its json file so check comma (,) and don't miss or keep extras like in *.ts files

注意:它是JSON文件,所以请检查逗号(,),不要遗漏或保留*.ts文件中的多余字符



{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": [],
"paths": {
"@app/*": ["src/app/*"],
"@chat/*": ["@app/chat/*"],
"@shared/*": ["@app/shared/*"],
"@auth/*": ["@app/auth/*"]
}
},
"files": [
"src/main.ts"
],
"include": [
"src/**/*.d.ts"
]
}


On top of Emily Zhai's comment, if someone wants to Restart TypeScript/ESLint Servers Automatically when configs changed on VS Code, my extension may help

除了Emily Zhai的评论,如果有人想要在VS Code上更改配置时自动重启TypeScrip/ESLint服务器,我的扩展可能会有所帮助


Auto Restart TypeScript / ESLint Servers - Visual Studio Marketplace

自动重新启动TypeScrip/ESLint服务器-Visual Studio Marketplace



Check your workspace


Check how you have opened your workspace in VScode.

检查您是如何在VScode中打开工作区的。


In my case, I have this structure:

在我的例子中,我有这样的结构:


├── my-proyect
│ ├── client* (this is my react folder)
│ └── server

To make it work, I have o open the client folder. If I open the whole project it doesn't work.

要使其正常工作,我必须打开客户端文件夹。如果我打开整个项目,它不起作用。


Other things to check:

其他需要检查的事项:



  1. tsconfig.json should be something like this


{
"compilerOptions": {
...
"baseUrl": "./src",
"paths": {
"~/*": ["./*"],
}
},
}


  1. vite.config.ts should be something like this (if you use vite)


import react from '@vitejs/plugin-react'
import path from 'path'
import { defineConfig } from 'vite'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'~': path.resolve(__dirname, 'src'),
},
},
})


Restart TS Server.

重新启动TS服务器。


In VSCode, you can press **Cmd/Ctrl + Shift + P** and search for Typescript: 


for parcel with react add compilerOptions.paths and add parcel-resolver-tspaths to resolvers for .parcelrc(create if not present) file.
or checkout Offical: https://parceljs.org/plugin-browser/?type=%22resolver%22&page=0&filter=%22resolver-path%22&includeOfficial=true

对于带有REACT的地块,为.parcelrc(如果不存在,则创建)文件的解析器添加编译器Options.路径,并添加parcel-solver-tspath。或结账官方网站:https://parceljs.org/plugin-browser/?type=%22resolver%22&page=0&filter=%22resolver-path%22&includeOfficial=true


npm install --save-dev parcel-resolver-tspaths

package.json


{
"compilerOptions": {
"paths": {
"@app/*": ["./src/app/*"],
"@utils/*": ["./src/utils/*"]
},
}
...
}

.parcelrc


{
"extends": "@parcel/config-default",
"resolvers": [
"...",
"parcel-resolver-tspaths"
],
...
}


If you have Javascript files, also check that in your tsconfig.json you have

如果您有Java脚本文件,也要在您的tsconfig.json中检查您有


 "allowJs": true

otherwise TypeScript will ignore .js and .jsx files imports

否则,Type脚本将忽略.js和.jsx文件导入



Make sure the path provided is correct. It will throw error "module and its decrations not found".

确保提供的路径正确。它将抛出错误“模块及其decrations未找到”。



For myself, after much trial and error the solution was simple. Remove this line from my tsconfig and it worked.

对我来说,经过多次试验和错误,解决方案很简单。从我的tsconfig中删除此行,它就起作用了。


"extends": [
"plugin:import/recommended",
]

and


"rules": {
"import/no-unresolved": "error",,
}

更多回答

For anyone else still having the problem even though having /* make sure your baseUrl is set, as I just spent hours trying to fix this.

对于任何其他仍然有这个问题的人,即使有/*,请确保您的base Url已经设置,因为我刚刚花了几个小时试图解决这个问题。

please edit this post and add what @ErraticFox said about the baseUrl. Thank you!

请编辑这篇文章,并添加@EraticFox对BasUrl的评论。谢谢!

In case anyone is using VSCode and having trouble getting the /* solution to work. Try Cmd+Shift+P > Typescript: Restart TS Server.

以防任何人在使用VSCode时遇到/*解决方案的问题。尝试Cmd+Shift+P>类型脚本:重新启动TS服务器。

@ErraticFox still not working with base url as "./'

@EraticFox仍然不能将基本url用作“./‘

thanks @EmilyZhai it did the trick for me!

谢谢@Emily Zhai,它帮了我大忙!

Note that you might need to be in a .ts file for that option to appear. (I had to be focused on a .ts file.)

请注意,您可能需要在.ts文件中才能显示该选项。(我必须专注于.ts文件。)

Restart worked for me using Webstorm - thanks!

使用WebStorm重启对我很有效--谢谢!

Thank you so so much!! Without this answer I don't know how much more time I would had spent surfing the web to solve this!

感谢你的评分如果没有这个答案,我不知道我会花多少时间上网来解决这个问题!

@DarkCrazy :) It has bitten me multiple times. So many hours wasted on what was just a simple restart

@DarkCrazy:)它咬了我好几次。在一次简单的重启上浪费了这么多时间

Typescript: Restart TS Server <- this should be in every tutorial that ever mentions adjusting baseUrl or paths..

TypeScrip:重新启动TS服务器<-这应该出现在每一篇提到调整BasUrl或路径的教程中。

Man! you are a lifesaver! I literally spent 2 days just on this small mistake!

哥们儿!你真是救命稻草!我真的花了两天的时间才犯了这个小错误!

Glad I could help. I think it's quite counter-intuitive, considering "include" and "exclude" (which are also relative paths) being placed in the object root.

很高兴能帮上忙。考虑到“Include”和“Exclude”(也是相对路径)被放在对象根中,我认为这是非常违反直觉的。

Omg, I was looking for this for 3 hours already, I was going nuts

天哪,我已经找了3个小时了,我都快疯了

This in combination with the /* magic at the end for BOTH the ALIAS ( @components /* )itself and the path made things work, except images - for those I had to add custom typing files as described here - stackoverflow.com/a/57129153/1835470 basically you create a special file in typings/custom/import-yourextension.d.ts in your project root

这与别名(@Components/*)本身和路径末尾的/*功能结合在一起,使得一切正常,除了图像-对于那些我必须添加此处所述的自定义键入文件-stackoverflow.com/a/57129153/1835470基本上,您可以在项目根目录中的键入/定制/IMPORT-yourextension.d.ts中创建一个特殊文件

Thank you, worked for me! Luckily I found this SO article rather quickly. Interesting: This worked before with Angular 9. With updating to Angular 12, I got Error: Module not found: Error: Can't resolve .... Now it's ok again !

谢谢,对我很管用!幸运的是,我很快就找到了这篇文章。有趣:这在以前的角度9起作用。当更新到角度12时,我得到错误:找不到模块:错误:无法解决...现在又好了!

just to mention, for module-alias might be required to install types also: npm i --save-dev @types/module-alias

顺便提一下,安装类型可能还需要使用模块别名:npm i--save-dev@type/模块别名

Wow! I though tsc would work out of the box! Thank you for clarifing

哇!我以为台积电可以开箱即用!感谢您的澄清

You can also add NODE_PATH=outDir before node start

您还可以在节点开始之前添加node_path=outDir

Thanks so much. Was about to pull my hair out.

非常感谢。正要把我的头发拔出来。

Thank you! This answer needs to get bumped higher!

谢谢!这个答案需要更高的评价!

Great explanation! Relevant Github issue: github.com/dividab/tsconfig-paths/issues/75

很好的解释!相关的Github问题:githorb.com/Dividab/tsconfig-路径/问题/75

Thankssss! this worked for me 'cause I use named imports :D

感恩节!这对我很有效,因为我使用命名导入:d

This helped out big time!!! thanks!

这帮了大忙了!谢谢!

if this is not working check stackoverflow.com/a/74719153/7668448. v4.0.0 have a bug. v4.0.1 fix it. Install with npm install vite-tsconfig-paths@latest

如果这不起作用,请检查stackoverflow.com/a/74719153/7668448。V4.0.0有一个错误。V4.0.1修复它。使用NPM进行安装安装vite-tsconfig-路径@Latest

Of all the solutions above, this is the one that worked for me with Vite.

在上面的所有解决方案中,这是对我有效的维生素E解决方案。

I had it working before, and numerous reloads didn't work. Complete close & reopen did!

我以前让它工作过,但多次重新加载都不起作用。完全关闭并重新打开完成!

Strange, but it works. I can confirm that. This advice saved me a lot of time.

很奇怪,但它很管用。我可以证实这一点。这个建议为我节省了很多时间。

What am I meant to see here if paths are working?

如果路径正常工作,我在这里应该看到什么?

This is not a solution and just removes the error. If the project is compiling without errors and eslint is still showing an error, then there is a misconfiguration in the eslint config.

这不是解决方案,只是删除了错误。如果项目编译没有错误,而eslint仍然显示错误,则说明eslint配置中存在配置错误。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com