繁体   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