【问题标题】:Use the webpack asset module with a custom output filename使用带有自定义输出文件名的 webpack 资产模块
【发布时间】:2021-01-17 15:31:05
【问题描述】:

假设我有以下 webpack.config.js 文件:

module.exports = {
    //...
    output: {
        filename: "[name].bundle.js",
        path: path.resolve(__dirname, "dist"),
        assetModuleFilename: "assets/[name][ext]",
    },
    module: {
        rules: [
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/i,
                type: "asset/resource",
            },
            {
                test: /\.(png|svg|jpg|jpeg|gif)$/i,
                type: 'asset/resource',
            },
        ],
    },
    plugins: [
    //...
    ],
};

我的问题是如何将字体与图像分开?我想把每一个放在 assets 文件夹下名为“fonts”和“images”的子目录中。我知道使用“文件加载器”可以做到这一点。但是,我想使用资产模块。

【问题讨论】:

    标签: javascript webpack


    【解决方案1】:

    您可以使用Rule.generator.filename 属性:

    module.exports = {
      // ...
    
      module : {
        rules : [
          // ...
    
          // Fonts
          {
            test      : /\.(woff2?|ttf|eot)(\?v=\w+)?$/,
            type      : 'asset/resource',
            generator : {
              filename : 'fonts/[name][ext][query]',
            }
          },
        ]
      },
    
      // ...
    }
    

    【讨论】:

    • 值得一提的是Rule.generator.filename也可以是filename: (pathData) => { /* do whatever */ return filename }这样的函数。 pathData 包含许多有用的信息,例如 pathData.module.resourceResolveData。这样就可以针对当前模块/资源的不同条件返回不同的文件名。
    【解决方案2】:

    这应该没问题。

          {
            test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
            use: [
              {
                loader: 'url-loader',
                options: {
                  limit: 8192,
                  name: '[hash:8].[name].[ext]',
                  outputPath: 'fonts/'
                }
              }
            ]
          },
          {
            test: /\.(png|jpe?g|gif|svg|webp|tiff)(\?.*)?$/,
            use: [
              {
                loader: 'url-loader',
                options: {
                  limit: 8192,
                  name: '[hash:8].[name].[ext]',
                  outputPath: 'images/'
                }
              }
            ]
          }
    

    【讨论】:

    猜你喜欢
    • 2017-05-20
    • 2021-05-25
    • 1970-01-01
    • 2017-03-02
    • 2020-11-03
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2020-12-09
    相关资源
    最近更新 更多