我有一个打字稿应用程序,其中有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的回答,但似乎没有用。
我在这里做什么错了?
答案 0 :(得分:0)
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.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/*")
}
},
// package.json
// ...
"alias": {
"utils": "./src/utils/*",
"operations": "./src/operations/*",
"actions": "./src/actions/*",
"components": "./src/components/*",
"constants": "./src/constants/*"
}