首页 > 解决方案 > 徽标 png 图像未通过 webpack 加载

问题描述

我希望显示徽标 png 文件

图像应该在 web pack 启动后立即加载我只能获取 HTML、css 和一些字体,而徽标不显示。

错误信息

Refused to apply style from 'http://localhost:8080/forkify/dist/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
test.js:5 Imported module
index.js:14 Uncaught ReferenceError: element is not defined
    at eval (index.js:14)
    at Module../src/js/index.js (bundle.js:398)
    at __webpack_require__ (bundle.js:432)
    at bundle.js:526
    at bundle.js:529
logo.png:1 Failed to load resource: the server responded with a status of 404 (Not Found)

我已经在 webpack 上尝试了文件和 uri 加载器,但仍然遇到同样的问题。

index.js

import num from './test';
import '../../dist/css/style.css';
import Logo from '../../dist/img/logo.png';

// Add the image to our existing div.
const myIcon = new Image();
myIcon.src = Logo;

element.appendChild(myIcon);

console.log(`I imported ${num} from another module test!`);

Webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports={
    entry:'./src/js/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename:'js/bundle.js'
    
    },
    // mode: 'development' // Dont compress or minify codes and enable quick loading
    devServer: {
        contentBase:'./dist'
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: './src/index.html'
        })
    ],
    module: {
        rules: [
          {
            test: /\.css$/i,
            use: ["style-loader", "css-loader"],
          },
          {
            test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
            // More information here https://webpack.js.org/guides/asset-modules/
            type: "asset/resource",
          },
        ],
    },

}; 

包.json

{
  "name": "forkify",
  "version": "1.0.0",
  "description": "Food app project",
  "main": "index.js",
  "scripts": {
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "start:dev": "webpack serve --mode development --open"
  },
  "author": "BrewedLeo",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^5.0.1",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.0.0",
    "style-loader": "^2.0.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.20.2",
    "webpack-cli": "^4.5.0",
    "webpack-dev-server": "^3.11.2"
  },
  "dependencies": {}
}

文件布局

标签: javascripthtmlcsswebpack

解决方案


我认为,您在 webpack.config.json 中错过了规则 outputPath 下的规则,例如在测试之后:/.(png|.... 而不是定义加载器:'file-loader',并插入路径:选项:{ outputPath:'images' , } 对我来说,使用 copy-webpack-plugin 比复制 dist 中的文件更容易。

plugins: [
        new CopyPlugin({
            patterns: [
                { from: "src/img", to: "img/" },
            ],
        }),
    ]

...并且缺少元素


推荐阅读