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

时间:2019-07-20 18:41:02

标签: javascript typescript webpack

我正在尝试将本地png图像导入ts webpack项目,但出现以下错误。

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

我所有其他模块都可以正常导入,即;我的css,svg和ts文件。它似乎只发生在png中。

我的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']
    }]
  }

我的tsconfig.json

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

我的进口声明

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

我的文件结构

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

3 个答案:

答案 0 :(得分:0)

尝试从此更改-

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

对此-

import Logo from 'images/logo.png';

答案 1 :(得分:0)

我在这里找到了答案。 Webpack & Typescript image import

这就是我所做的。

添加了新目录和import-png.d.ts文件

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

import-png.d.ts

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

将我的文件加载器模块更改为此:

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

现在,我可以输入如下语句:

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

答案 2 :(得分:0)

我的错误是我排除了引用react-app-env.d.ts:

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

由于间隔注释规则,Eslint迫使我这样做。

希望这对某人有帮助。