webpack无法使用资产/资源中的outputPath加载资源

3pmvbmvn  于 2022-11-13  发布在  Webpack
关注(0)|答案(1)|浏览(188)

我不是很熟悉Webpack。
我的目标是将HTML中的所有资产放在一个特定的文件夹中。
为此,我在处理'类型的规则下设置了一个新选项:资产/资源:

{
  test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
  type: 'asset/resource',
  generator: {
    outputPath: 'assets/' // this is the new option setted
  }
}

webpack会在编译后创建文件夹,并将这些文件放入其中。问题是编译的HTML文件不知道assets文件在assets/文件夹中。
我该如何修复它?
这是我的webpack.config.js

const path = require('path')
const { merge } = require('webpack-merge')

const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin')

const stylesHandler = MiniCssExtractPlugin.loader

const base = {
    entry: {
        bundle: [
            './js/main.js',
            './css/style.scss'
        ]
    },
    output: {
        path: path.resolve(__dirname, 'docs')
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'index.html',
            scriptLoading: 'module',
            inject: 'body'
        }),
        new MiniCssExtractPlugin()
    ],
    module: {
        rules: [
            {
                test: /\.s[ac]ss$/i,
                use: [stylesHandler, 'css-loader', 'postcss-loader', 'sass-loader'],
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
                type: 'asset/resource',
                generator: {
                    outputPath: 'assets/' // this is the new option setted
                }
            },
            {
                test: /\.html$/i,
                use: ['html-loader']
            }
        ]
    }
}

const dev = {
    devServer: {
        open: false,
        host: 'localhost',
        watchFiles: ['./index.html']
    }
}

const prod = {
    output: {
        clean: true
    }
}

module.exports = (env, args) => {
    switch (args.mode) {
        case 'development':
            return merge(base, dev)
        case 'production':
            return merge(base, prod)
        default:
            throw new Error('No matching configuration was found!')
    }
}
gwbalxhn

gwbalxhn1#

所以我自己发现的,而且很明显。
好吧,当webpack编译你的index.html文件时,它不会理解你是否只是为你的资产的最终命运给予了一个新的路径。
例如,就像我所做的:

{
  test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
  type: 'asset/resource',
  generator: {
    outputPath: 'assets/' // this is the new option set
  }
}

要使其正常工作,您需要指定publicPath

{
  test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
  type: 'asset/resource',
  generator: {
    outputPath: 'assets/' // this is the new option set
    publicPath: 'assets/'
  }
}

你告诉网络包:
1.将所有资产放入outputPath中。
1.嘿,HTML,当你寻找资产时,请在寻找之前包括publicPath

相关问题