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

时间:2018-09-12 01:06:16

标签: webpack-dev-server webpack-4 webpack-file-loader

我正在使用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'
      })
    ]
  },
};

1 个答案:

答案 0 :(得分:1)

如果有人从Google来,我就把它留在这里。 您必须告诉打字稿png图像是一个模块。 这样做的方法是在assets文件夹中,或者在您存储图像的任何地方创建一个名为index.d.ts

的文件。

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

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

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