Webpack resolve.alias does not work with typescript?

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!