在不导航相对路径的情况下从单独的目录导入打字稿模块?
Importing typescript modules from a separate directory without navigating the relative path?
我有以下这个打字稿文件 src/main/ts/hello.ts
包含:
export function hello() {
return 'Hello World!';
}
export default hello;
对应的测试在src/test/ts/hello.spec.ts
中。它像这样导入 hello
:
import hello from 'hello';
IIUC 下面的配置应该允许我在测试中导入 hello.ts
而无需使用相对路径。
{
"include": [
"src/main/ts/**/*.ts"
],
"exclude": [
"node_modules"
],
"baseUrl": ".",
"paths": {
"*": [
"*", "src/main/ts/*"
]
},
"compilerOptions": {
"experimentalDecorators": true,
"noImplicitAny": true,
"moduleResolution": "node",
"target": "es6"
}
}
但是我仍然收到此错误:
src/test/ts/hello.spec.ts(1,19): error TS2307: Cannot find module 'hello'.
想法?
您可以在 tsconfig.json
中指定 baseUrl
和 paths
属性:
{
"include": [
"src/main/ts/**/*.ts",
"src/test/ts/**/*.ts"
],
"exclude": [
"node_modules"
],
"compilerOptions": {
"experimentalDecorators": true,
"noImplicitAny": true,
"moduleResolution": "node",
"target": "es6",
"baseUrl": ".",
"paths": {
"*": [
"*", "src/main/ts/*"
]
}
}
}
文档:https://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url
我有以下这个打字稿文件 src/main/ts/hello.ts
包含:
export function hello() {
return 'Hello World!';
}
export default hello;
对应的测试在src/test/ts/hello.spec.ts
中。它像这样导入 hello
:
import hello from 'hello';
IIUC 下面的配置应该允许我在测试中导入 hello.ts
而无需使用相对路径。
{
"include": [
"src/main/ts/**/*.ts"
],
"exclude": [
"node_modules"
],
"baseUrl": ".",
"paths": {
"*": [
"*", "src/main/ts/*"
]
},
"compilerOptions": {
"experimentalDecorators": true,
"noImplicitAny": true,
"moduleResolution": "node",
"target": "es6"
}
}
但是我仍然收到此错误:
src/test/ts/hello.spec.ts(1,19): error TS2307: Cannot find module 'hello'.
想法?
您可以在 tsconfig.json
中指定 baseUrl
和 paths
属性:
{
"include": [
"src/main/ts/**/*.ts",
"src/test/ts/**/*.ts"
],
"exclude": [
"node_modules"
],
"compilerOptions": {
"experimentalDecorators": true,
"noImplicitAny": true,
"moduleResolution": "node",
"target": "es6",
"baseUrl": ".",
"paths": {
"*": [
"*", "src/main/ts/*"
]
}
}
}
文档:https://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url