4
votes

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!

1
Does it work if you instead do import { MyNamespace } from 'libname'; ? - Axnyff
No... in that case I get tsc complaining that "TS2306: File 'C:\project\node_modules\@types\libname\custom.d.ts' is not a module." and it errors out in the IDE as well with that same message. So it finds it, but can't import that way. - Edy Bourne
I wonder if it's a problem with your third party typings, does it have exports in it ? However, I think you might be able to bypass this problem by declaring a specific loader for your library, maybe the null-loader: webpack.js.org/loaders/null-loader - Axnyff
@Axnyff this was it! The null-loader did it. If you want to move it to an answer I can accept it. Thank you! - Edy Bourne

1 Answers

1
votes

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