如何让 WebStorm 中的 TypeScript 解析 webpack 的别名?

How can make TypeScript in WebStorm to parse alias of webpack?

我在带有 webpack (2.6.1) 的 WebStorm (2017.3) 中使用 TypeScript (2.6.2)。

我创建了一些 webpack 的别名:

//webpack.config.js
resolve: {
  alias: {
    '@': path.resolve(__dirname, '../')
  },
},

当我在 TypeScript 中使用别名时,WebStorm 告诉我一些错误消息:

TS2307: Cannot find module '@/src/short-night/Axis'.

但是通过webpack

项目可以运行不报错

我在 WebStorm 设置中选择了 webpack.config.jstsconfig.json

完整项目见github: pea3nut/timeline

我该怎么做才能让 WebStorm 理解这样的别名?

tsconfig.json中使用Path mapping是正确的方法。你已经设置好了。但问题是您的 TypeScript 文件位于 tsconfig.json 所在目录的父文件夹中。因此,您的 tsconfig.json 中包含的唯一 .ts 文件是 develop/main.ts。 来自 https://www.typescriptlang.org/docs/handbook/tsconfig-json.html:

The presence of a tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project. If the "files" and "include" are both left unspecified, the compiler defaults to including all TypeScript (.ts, .d.ts and .tsx) files in the containing directory and subdirectories except those excluded using the "exclude" property. 

因此,您必须将 tsconfig.json 移动到项目根目录并相应地更改那里的路径:

{
  "compilerOptions": {
    "outDir": "./develop/dist/",
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "moduleResolution": "node",
    "lib": ["es2015", "es2017", "dom"],
    "baseUrl":".",
    "paths": {
      "@/*" :["./*"]
    },
    "allowJs": true
  }
}