可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I try to shorten my imports in typescript
from import {Hello} from "./components/Hello";
to import {Hello} from "Hello";
For that I found out you can use resolve.alias
in webpack thus I configured that part as following
resolve: { root: path.resolve(__dirname), alias: { Hello: "src/components/Hello" }, extensions: ["", ".ts", ".tsx", ".js"] },
Webpack builds, and the output bundle.js works. However typescript's intellisense complain it cannot find the module
So my question is whether or not webpack's resolve.alias works with typescript?
I found following issue but there's no answer to it.
回答1:
If you're using ts-loader
, you might have to synchronize your webpack alias
/resolve
settings with your paths
setting in your tsconfig.json
.
{ "compilerOptions": { "baseUrl": "./", "paths": { "Hello": ["src/components/Hello"] } } }
If you're using awesome-typescript-loader
, then webpack can figure this out automatically from the paths
setting in your tsconfig.json
, as per the status on this issue from the repo. That way, you don't need to duplicate the same information in your Webpack alias
field.
回答2:
Dudes, you are missing one very important point in tsconfig.json: The matching pattern!
It should be configured like this:
"baseUrl": ".", "paths": { "appSrc/*": [ "src/*" ] }
The "*" is the important part to tell TS to match anything on the right side.
I found that out from this article: https://medium.com/@martin_hotell/type-safe-es2015-module-import-path-aliasing-with-webpack-typescript-and-jest-fe461347e010
回答3:
I think you can do this and have it work the way you describe:
resolve: { root: [ path.resolve(__dirname), <path_to_components_directory> //e.g. path.resolve(__dirname, 'src', 'components') ], extensions: ["", ".ts", ".tsx", ".js"] },
Then you can do import {Hello} from "Hello";
I know I do this to resolve file paths in my src/js
directory. I am not using typescript though, but I don't think it would affect the result.