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.
For those of you who like to work with TypeScript, webpack offers the possibility to use a configuration file written in TypeScript. Webpack v5 already ships with TypeScript definitions, so you don't have to install @types/webpack but you need to install typescript, ts-node and @types/node.
Package configuration After running the build command, webpack will transpile the two TypeScript files into JavaScript code and generate a bundle. js file inside the dist folder.
Like Babel, Webpack depends on TSC to transpile TypeScript to JavaScript but as TSC doesn't have a clue about Webpack, hence Webpack needs a loader to talk to TSC. This is where the ts-loader comes into play. Webpack compiles a TypeScript file using ts-loader package which asks TSC to do the compilation.
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
webpack.config.js
are updated (e.g. if you use storybook). If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With