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

时间:2017-12-22 14:57:22

标签: typescript webpack webstorm

我在WebStorm(2017.3)中使用TypeScript(2.6.2)和webpack(2.6.1)。

我创建了一些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理解这些别名?

1 个答案:

答案 0 :(得分:1)

tsconfig.json中使用Path mapping是正确的方法。你已经建立了它。但问题是您的TypeScript文件位于tsconfig.json所在目录的父文件夹中。因此,.ts中包含的唯一tsconfig.json文件为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
  }
}

enter image description here