How to use query param import in webpack with typescript without getting Cannot find module?

Viewed 1118

import a from 'a.png?sizes[]=64'

but I get a ts error Cannot find module 'a.png?sizes[]=64'. All works with webpack, but tsc check types fails because there is no file like that. That should only check for a.png with query param.

Any ideas how to do that? I run this command to check types tsc --project ./tsconfig.json --noEmit

One hack is to use require() syntax but that will skip any checks. So even if the file is missing, no error will happen.

2 Answers

Adding additional declaration helped, but there must be a better way.

e.g. types/import-png.d.ts

declare module '*.png' {
  const value: string;

  export default value;
}

declare module '*.png?inline' {
  const value: string;

  export default value;
}

I solved this issue by adding an extra parameter to the url and matching on it.

declare module '*&useResponsiveLoader=true' {
    const defaultExport: {
        srcSet: string,
        images: {
            height: number;
            width: number;
            path: string;
        }[],
        src: string,
        placeholder: string,
        toString(): string
    };
    export default defaultExport;
}

This works because responsive loader does allow unused properties according to its validation schema (both the current and next versions)

You then import the file as

import a from 'a.png?sizes[]=64&useResponsiveLoader=true'
import b from 'b.png?sizes[]=64,sizes[]=128&useResponsiveLoader=true'

(Note that responsive loader 5 requires more tweaks to get working with Webpack 5, I'm still figuring these out)

Related