4

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!

4
  • Does it work if you instead do import { MyNamespace } from 'libname'; ? Commented Jul 1, 2020 at 17:14
  • 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. Commented Jul 1, 2020 at 17:32
  • 1
    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 Commented Jul 1, 2020 at 17:48
  • 1
    @Axnyff this was it! The null-loader did it. If you want to move it to an answer I can accept it. Thank you! Commented Jul 1, 2020 at 19:03

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.