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

问题描述 投票:1回答:1

我在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了解这样的别名?

typescript webpack webstorm
1个回答
1
投票

Path mapping使用tsconfig.json是正确的方法。你已经建立了它。但问题是您的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

© www.soinside.com 2019 - 2024. All rights reserved.