Webpack resolve.alias does not work with typescript?
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.
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: Type-safe es2015 module import path aliasing with Webpack, Typescript and Jest
NOTE
- Make sure all your
webpack.config.js
are updated (e.g. if you use storybook). - If you use Visual Studio Code you may need to restart it, in order for the squiggly lines to disappear.
As others have mentioned, you need to provide an alias
in your webpack.config.js:
resolve: {
extensions: [".ts", ".js"],
alias: {
forms: path.resolve(__dirname, "src/forms/")
}
},
This needs to be in synch with your tsconfig.json
file (baseUrl and paths are required).
"compilerOptions": {
baseUrl: "./",
...
paths: {
"forms/*": ["src/forms/*"]
}
}
Note: The wildcard pattern is necessary to match with your resolve alias configuration.
Then you can import any library using your alias:
import { FormsModule } from "forms/my-forms/my-forms.module";