javascript - Babel/Typescript 别名无法正常工作

标签 javascript node.js typescript gulp babeljs

我有一个使用 Gulp、tsify、browserify 和 babelify 编译的 Typescript 环境。我已成功配置别名以更好地导航项目。

我正在尝试导入一个 Node 模块,比方说query-string,通过这样做导入component.ts:

从“查询字符串”导入 * 作为查询字符串;

tsconfig.jsontraceResolution 选项向我展示了这一点:

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"
      }
    }]
  ]
}

这是真正起作用的:

  1. 使用相对路径导入 .ts 文件
  2. 使用别名导入 .ts 文件(例如 import '@component/example-component/component.ts')
  3. 将 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/

相关文章:

javascript - 我怎样才能用angularjs改变选项值

node.js - 使用 express-namespace 调用两次中间件的 Express 请求

typescript - 参数中的泛型和typeof T

javascript - 使用解析器组合器解析简单的数学表达式

typescript - 需要特定字符串作为 TypeScript 接口(interface)中的可选键

javascript - photoswipe 自定义工具栏与 jquery 移动

javascript - 使用 mongoose 防御 XSS 攻击

javascript - 用不重复的随机数填充数组

javascript - nodejs 中的 for 循环不适用于 redis hexists

node.js - 无法使用 sequelize 从本地 Node 应用程序连接到 heroku postgresql 数据库