簡體   English   中英

Webpack 5 沒有在.js文件中加載圖像

[英]Webpack 5 not loading images in .js files

我正在制作一個必須通過第三方站點進行測試的模塊。

一切正常,除了Webpack不會構建我在.js文件中添加的任何圖像文件。 我無法導入圖像,因為圖像太多並且它們被變量選擇。 我無法弄清楚為什么圖像不會構建。

我也嘗試過文件加載器和 url-loader,沒有任何效果。

react 文件中的返回

return (<div><img src="/src/images/screenshot.png" /></div> )

這是配置:

module.exports = {
    mode: isProd ? "production" : "development",
    entry: "./src/index.js",
    module: {
        rules: [

{測試:/.(jpe?g|png|svg|gif|ico|eot|ttf|woff|woff2|mp4|mp3|pdf|webm|txt)$/i,使用:[{加載器:“文件加載器", }, ], }, { 測試:/.(jpe?g|png|svg|gif|ico|eot|ttf|woff|woff2|mp4|mp3|pdf|webm|txt)$/,輸入:"資產/資源”,生成器:{ 文件名:“靜態/塊/[路徑][名稱].[哈希][ext]”,},},

            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader",
                    options: {
                        plugins: [
                            "syntax-dynamic-import",
                            "transform-react-jsx",
                        ],
                    },
                },
            },
            {
                test: /\.(css|scss|sass)$/,
                use: ["style-loader", "css-loader", "sass-loader"],
            },
        ],
    },
    plugins: [
        new webpack.DefinePlugin({
            __PUBLIC_PATH__: JSON.stringify(publicPath),
        }),
    ],
    output: {
        filename: "[name].js",
        chunkFilename: "[name].chunk.js",
        path: buildPath,
        publicPath,
    },
    devServer: {
        static: {
            directory: buildPath,
            watch: true,
        },
        historyApiFallback: true,
        headers: {
            "Access-Control-Allow-Origin": "*",
        },
        client: {
            logging: "log",
            reconnect: false,
            webSocketURL: "ws://localhost:8080",
        },
    },
};

對於要由 webpack 處理的圖像,您應該使用file-loader

使用$ npm install file-loader --save-dev安裝它。

然后將此規則添加到您的 webpack 配置中:

    rules: [
      {
        test: /\.(jpe?g|png|svg|gif|ico|eot|ttf|woff|woff2|mp4|mp3|pdf|webm|txt)$/i,
        use: [
          {
            loader: 'file-loader',
          },
        ],
      },
    ],

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM