javascripttypescriptwebpacktypescript-typingswebpack.config.js

Webpack can't find import needed for Typescript type resolution. How to fix this?


My project uses typescript and built with webpack.

I have a typings file that comes from a third part lib located under node_modules/@types/libname/custom.d.ts. That file has a namespace declaration with a few types in it:

declare namespace MyNamespace {
    export type A = ...;
}

Then in order to be able to use that type in my typescript code like so:

const x: MyNamespace.A;

...I need to add the import declaration as follows somewhere in the app:

import 'libname'

Which tsc resolves correctly to node_modules/@types/libname/custom.d.ts so everything works if I compile with tsc.

However webpack then can't build. It can't understand this import:

ERROR in ./Index.tsx
Module not found: Error: Can't resolve 'libname' in 'C:\<path_to_index_file>'
 @ ./Index.tsx 44:0-32

I tried to add an alias in my webpack.config like so:

    resolve: {
        alias: Object.assign({
            'libname$': path.resolve(__dirname, 'node_modules/@types/libname/custom.d.ts'),
        }
    },

But then it fails because it can't understand that file's syntax and asks if I'm missing a loader.

How can I fix this so that webpack will understand this typings import statement?

I'm on webpack version 4.41.6

Thanks!


Solution

  • You should use the null-loader for this import so webpack will ignore it.