我有一个使用 Gulp、tsify、browserify 和 babelify 编译的 Typescript 环境。我已成功配置别名以更好地导航项目。
我正在尝试导入一个 Node 模块,比方说query-string
,通过这样做导入component.ts
:
从“查询字符串”导入 * 作为查询字符串;
tsconfig.json
的 traceResolution
选项向我展示了这一点:
Module name 'query-string' was successfully resolved to '/node_modules/query-string/index.js'
但我仍然在控制台中收到错误消息:
Error: Cannot find module 'query-string' from '/components/example-component/'
想象一下这样的项目结构:
/
|-- node_modules/
|
|-- ts/
| |-- app.ts //this is the main file, it imports component.ts
|
|-- components/
| |-- example-component/
| |-- component.html
| |-- component.ts //attempting to import a node module here
|
|-- gulpfile.js
|-- tsconfig.json
|-- .babelrc
|-- package.json
我的 tsconfig.json
文件如下所示:
{
"compilerOptions": {
"noImplicitAny": false,
"target": "es2015",
"sourceMap": true,
"baseUrl": "./ts",
"traceResolution": true,
"paths": {
"@components/*": ["../components/*"],
"*": ["../node_modules/*"]
}
}
}
我的 .babelrc
看起来像这样:
{
"presets": ["es2015"],
"plugins": [
["module-resolver", {
"cwd": "babelrc",
"root": ["./ts"],
"alias": {
"@components": "./components"
}
}]
]
}
这是真正起作用的:
- 使用相对路径导入
.ts
文件 - 使用别名导入
.ts
文件(例如import '@component/example-component/component.ts'
) - 将 Node 模块导入
app.ts
最佳答案
成功定位模块的入口点(根据您提供的 traceResolution
消息正确发生的事情)与理解该模块是不同的问题。
为了让 TypeScript 理解模块,它需要找到一个描述模块类型的类型文件 (.d.ts
)。
查看 query-string repo ,它不附带 .d.ts
文件,因此您需要从其他地方将其拉入。
然而,查询字符串的类型似乎在 Definitely Typed repo 中可用。 ,这意味着您应该能够运行 npm install --save-dev @types/query-string
并且类型将添加到您的项目中。
关于javascript - Babel/Typescript 别名无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48318302/