导入时 Webpack 找不到图像 - 找不到模块

Webpack cannot find image when imported - module not found

我正在使用 webpack 开发服务器来提供一个简单的 Typescript 应用程序。在其中,我试图像这样在 Typescript 中动态加载图像:

import img from "./image.png";

const myImg = new Image();
myImg.addEventListener("load", ...);
myImg.src = img;

HTML、TS、图片文件都是挨着的,所以我用相对路径抓取图片。然而,webpack 抱怨说“./image.png”不是一个模块。我几乎可以肯定这一定是配置问题。以下是相关文件(部分值更改为通用值):

package.json

{
  "name": "my_project",
  "version": "0.1.0",
  "description": "My project",
  "main": "index.js",
  "scripts": {
    "build-prod": "webpack --config webpack.prod.js",
    "start-dev": "webpack-dev-server --config webpack.dev.js"
  },
  "author": "Cyle Ven Dawson",
  "license": "MIT",
  "private": true,
  "devDependencies": {
    "awesome-typescript-loader": "^5.2.1",
    "css-loader": "^1.0.0",
    "file-loader": "^2.0.0",
    "html-webpack-plugin": "^3.2.0",
    "node-sass": "^4.9.3",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.0",
    "tslint": "^5.11.0",
    "typescript": "^3.0.3",
    "webpack": "^4.17.2",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.8",
    "webpack-merge": "^4.1.4"
  }
}

webpack.dev.js

const merge = require("webpack-merge");

const commonConfig = require("./webpack.common");

module.exports = merge(
  commonConfig,
  {
    "devServer" : {
      "allowedHosts": [
        "dev.example.com"
      ],
      "disableHostCheck": true,
      "host": "1.2.3.4",
      "port": 12345,
      "public": "dev.example.com:12345"
    },
    "mode": "development"
  }
);

webpack.common.js

const HtmlWebPackPlugin = require("html-webpack-plugin");
const TsConfigPathsPlugin = require("awesome-typescript-loader").TsConfigPathsPlugin;

module.exports = {
  "entry": "./src/index.ts",
  "module": {
    "rules": [
      {
        "include": /src/,
        "test": /\.ts$/,
        "use": {
          "loader": "awesome-typescript-loader"
        }
      },
      {
        "include": /src/,
        "test": /\.scss$/,
        "use": [
          "style-loader",
          "css-loader",
          "sass-loader"
        ]
      },
      {
        "include": /src/,
        "test": /\.(png|svg|jpg|gif)$/,
        "use": [
          'file-loader'
        ]
      }
    ]
  },
  "output": {
    "publicPath": "/"
  },
  "plugins": [
    new HtmlWebPackPlugin({
      "filename": "./index.html",
      "template": "./src/index.html"
    })
  ],
  "resolve": {
    "extensions": [".ts", ".js"],
    "plugins": [
      new TsConfigPathsPlugin({
        tsconfig: __dirname + '/tsconfig.json',
        compiler: 'typescript'
      })
    ]
  },
};

我把它留在这里以防有人从 google 来这里。 您必须告诉打字稿 png 图像是一个模块。 你这样做的方法是在 assets 文件夹内或者你存储图像的地方创建一个名为 index.d.ts

的文件

在此文件中放入以下内容:

declare module '*.png' {
  const value: any
  export = value;
}

这将使您能够将 png 图像作为模块导入并使 Typescript 满意。我相信这适用于 .wav、.gif、.jpg 等。您只需要在 index.d.ts 文件中声明每一个。 我希望这对某些人有所帮助。