gpt4 book ai didi

typescript 找不到路径中定义的模块

转载 作者:行者123 更新时间:2023-12-04 13:40:03 24 4
gpt4 key购买 nike

我有一个 typescript 应用程序,它有 paths对于绝对进口。我的 tsconfig 看起来像这样:

{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"utils*": ["src/utils*"],
"operations*": ["src/operations*"],
"actions*": ["src/actions*"],
"components*": ["src/components*"],
"constants*": ["src/constants*"],
},
"outDir": "dist",
"module": "esnext",
"target": "esnext",
"moduleResolution": "node",
"noEmit": true,
"lib": ["es2017", "dom"],
"noUnusedLocals": true,
"sourceMap": true,
"skipLibCheck": true,
"allowJs": true,
"jsx": "preserve",
"noUnusedParameters": true,
"preserveConstEnums": true,
"strict": true,
"allowSyntheticDefaultImports": true,
"noImplicitAny": true,
},
"exclude": [
"node_modules",
"dist",
],
"include": [
"./src/**/*"
],
"files": [
"./typings/index.d.ts"
]
}

我正在尝试使用这样的导入:
import { AppStateType } from 'actions/app';

但是我得到 cannot find module 'actions/app'
我关注了 this回答,但似乎没有用。

我在这里做错了什么?

最佳答案

图案为paths有点挑剔。

尝试这个:

"paths": {
"utils/*": ["src/utils/*"],
"operations/*": ["src/operations/*"],
"actions/*": ["src/actions/*"],
"components/*": ["src/components/*"],
"constants/*": ["src/constants/*"],
},

请注意添加了斜杠。

既然你有 baseUrl我认为这应该可行,但如果不是,下一步可能是指定完整的相对路径(相对于 tsconfig 文件):
"paths": {
"utils/*": ["./src/utils/*"],
"operations/*": ["./src/operations/*"],
"actions/*": ["./src/actions/*"],
"components/*": ["./src/components/*"],
"constants/*": ["./src/constants/*"],
},

这将满足 TypeScript 编译器的要求,但是如果您使用 Webpack 或 Parcel,您可能会提示他们无法找到文件,即使 TypeScript 编译得很好。在这种情况下,您需要为打包程序设置别名。它看起来有点像这样:

Webpack
// webpack.config.js or similar
// ...
resolve: {
extensions: [".js", ".jsx"], // import without .js, .jsx, .json extensions
alias: {
"utils": path.resolve(__dirname, "src/utils/*"),
"operations": path.resolve(__dirname, "src/operations/*"),
"actions": path.resolve(__dirname, "src/actions/*"),
"components": path.resolve(__dirname, "src/components/*"),
"constants": path.resolve(__dirname, "src/constants/*")
}
},

Parcel
// package.json
// ...
"alias": {
"utils": "./src/utils/*",
"operations": "./src/operations/*",
"actions": "./src/actions/*",
"components": "./src/components/*",
"constants": "./src/constants/*"
}

关于 typescript 找不到路径中定义的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58548002/

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