Importing images in TypeScript React - “Cannot find module”

前端 未结 5 1579
南笙
南笙 2020-12-29 01:59

I am trying to import images to use inside a React component with TypeScript. The bundler I\'m using is Parcel (not Webpack).

I have created a .d.ts fil

相关标签:
5条回答
  • 2020-12-29 02:37

    If you literally wrote "include": ["./src/index.d.ts"] in tsconfig.json and you don't have a "files" setting, that means the project defined by tsconfig.json includes only the single file ./src/index.d.ts. When you open any other file in VS Code, VS Code uses a separate language service instance that doesn't use your tsconfig.json. Adjust your "include" setting to match all the .ts and .tsx files in your project, or just delete it and rely on the default behavior of including all files under the directory containing tsconfig.json.

    Round 2

    TypeScript is ignoring index.d.ts because it assumes that index.d.ts is generated from index.tsx and index.tsx is more likely to be up to date. Name your index.d.ts file something else, e.g., declaration.d.ts.

    0 讨论(0)
  • 2020-12-29 02:45

    Create module/type

    # src/types/images.d.ts
    declare module '*.jpeg';
    declare module '*.jpg';
    declare module '*.jpeg';
    

    Change tsconfig.json

    {
        "compilerOptions": {
            "typeRoots" : ["node_modules/@types", "src/types"]
        }
    }
    
    0 讨论(0)
  • 2020-12-29 02:49

    I've pasted:

    // eslint-disable-next-line spaced-comment
    /// <reference types="react-scripts" />
    

    from an older project in my: react-app-env.d.ts and it worked.

    0 讨论(0)
  • 2020-12-29 02:50

    create index.d.ts file in folder src,and add this line

    declare module '*.jpg';
    
    0 讨论(0)
  • 2020-12-29 02:52

    there is a work around to it for example,

    import logo from "../../assets/logo.png"
    
    

    change this to

    const logo =  require("../../assets/logo.png")
    
    0 讨论(0)
提交回复
热议问题