【问题标题】:file-loader for fonts configuration in Webpack用于 Webpack 中字体配置的文件加载器
【发布时间】:2023-03-15 17:54:01
【问题描述】:

项目结构

/dev
-/fonts
-/css
  -/vendors
    -/fontawesome
      -/webfonts
/dist
-/my-project
  -/fonts

file-loader 用于 Webapck,我正在尝试使用 url 路径编译所有 sass/scss,并将所有字体文件移动到 dist/my-project/fonts/

webpack.config.js

module.exports = env => {
    ...
    return{
        ...
        output: {
            path: path.resolve(__dirname, 'dist/'),
        },
        module: {
            rules: [
            {
                test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]',
                            outputPath: './my-project/fonts/',
                            context: './fonts/'
                        }
                    }
                ]
            },
            {
                test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]',
                            outputPath: './my-project/fonts/',
                            context: 'css/vendors/'
                        }
                    }
                ]
            }
            ]
        }
    }
}          

此配置设法将文件复制到正确的位置,但在 css 中,我得到了:

@font-face{
   font-family:'Font Awesome 5 Brands';
   font-style:normal;
   font-weight:normal;
   font-display:auto;
   src:url(my-project/fonts/fa-brands-400.eot); //<--instead of fonts/fa-brands-400.eot
   ...
}

那么如何在 css 文件中编译正确的 url 字体路径来保留这个 outPath 呢?

【问题讨论】:

    标签: path webpack-4 webpack-file-loader


    【解决方案1】:

    解决方案是使用:

    • publicPath以css url字体编译路径
    • outPath将字体文件移动到正确目录

    所以...

    {
        test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
        use: [
            {
                loader: 'file-loader',
                options: {
                    name: '[name].[ext]',
                    publicPath: './fonts/', //<--resolve the path in css files
                    outputPath: './my-project/fonts/', //<-- path to place font files
                    context: 'css/vendors/'
                }
            }
        ]
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-07
      • 2017-06-02
      • 2018-02-27
      • 2016-10-18
      • 1970-01-01
      • 2020-09-25
      • 2017-06-12
      • 1970-01-01
      相关资源
      最近更新 更多