简体   繁体   English

TS2307:找不到模块“./images/logo.png”

[英]TS2307: Cannot find module './images/logo.png'

I'm trying to import a local png image into my ts webpack project, and I get the following error.我正在尝试将本地 png 图像导入到我的 ts webpack 项目中,但出现以下错误。

TS2307: Cannot find module './images/logo.png'.

All my other modules are importing just fine, ie;我所有的其他模块都可以正常导入,即; my css, svg and ts files.我的 css、svg 和 ts 文件。 It only seems to happen with png.它似乎只发生在 png 上。

My webpack.config.js modules section我的 webpack.config.js 模块部分

module: {
    rules: [{
      test: /\.ts$/,
      use:['ts-loader']
    },{
      test: /\.css$/,
      use: ['style-loader', 'css-loader']
    },{
      test: /\.(woff|woff2|eot|ttf|svg)$/,
      use: ['url-loader?limit=100000']
    },{
      test: /\.png$/,
      use: ['file-loader']
    }]
  }

My tsconfig.json我的 tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "module": "CommonJS",
    "target": "ES5",
    "lib": ["DOM", "ES2015.Promise", "ES5"],
    "allowJs": true,
    "alwaysStrict": true
  }
}

My import statement我的进口声明

import Logo from './images/logo.png';

My file structure我的文件结构

root
-src
--css
--images
---logo.png
--index.ts
--templates.ts
-package.json
-tsconfig.json
-webpack.config.js

I found the answer here.我在这里找到了答案。 Webpack & Typescript image import Webpack 和 Typescript 图像导入

Here's what I did.这就是我所做的。

Added a new directory and a import-png.d.ts file添加了一个新目录和一个 import-png.d.ts 文件

root
-typings
--custom
---import-png.d.ts

import-png.d.ts导入-png.d.ts

declare module "*.png" {
  const value: any;
  export default value;
}

changed my file-loader module to this:将我的文件加载器模块更改为:

{
      test: /\.(png|jpe?g|gif|jp2|webp)$/,
      loader: 'file-loader',
      options: {
        name: 'images/[name].[ext]'
      }

and now I can import with a statement like this:现在我可以用这样的语句导入:

import Logo from './images/logo.png'

My mistake was that I excluded the reference react-app-env.d.ts:我的错误是我排除了参考 react-app-env.d.ts:

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

Eslint has pushed me to do this because of the spaced-comment rule.由于间隔注释规则,Eslint 促使我这样做。

Hope this helps someone.希望这可以帮助某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM