Webpack无法加载@font-face字体

8

在我的React应用程序中,我正在实现服务器端渲染,因此由于性能问题,我不想在服务器端添加node_modules。但是,我希望从作为UI Kit库使用的node_modules中获取css。因此,我在我的webpack.server.config文件中使用了webpack nodeExternal,如下所示:

const path = require('path');
const merge = require('webpack-merge');
const baseConfig = require('./webpack.base.js');
const nodeExternals = require('webpack-node-externals')
let test = {
    test: /\.css$/,
    loader: 'css/locals?module&localIdentName=[name]__[local]___[hash:base64:5]'
}   


const config = {
    target:'node',
    entry: './src/index.js',

    output:{
        filename:'bundle.js',
        path:path.resolve(__dirname,'build')
    },
    externals: [nodeExternals({
        whitelist: [/\.(?!(?:jsx?|json)$).{1,5}$/i]
    })]
}

module.exports  = merge(baseConfig,config)

这里使用 webpack 添加 css 文件,但是从我的 node_modules UI kit 文件中加载 @font-face 时出现了问题。如果我从 webpack.server.config 文件中移除 nodeExternal,则一切都正常工作,但 bundle.js 文件大小会增加。
我已经在我的 webpack.base.config 文件中添加了 字体规则

const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CSSExtract = new ExtractTextPlugin('styles.css');


module.exports ={
    module: {
        rules: [{
            loader: 'babel-loader',
            test: /\.js$/,
            exclude: /node_modules/
        }, {
            test: /\.s?css$/,
            use: CSSExtract.extract({
                use: [
                    {
                        loader: 'css-loader',
                        options: {
                            sourceMap: true
                        }
                    },
                    {
                        loader: 'sass-loader',
                        options: {
                            sourceMap: true
                        }
                    }
                ]
            })
        },{
            test: /\.(gif|svg|jpg|png|ttf|eot|woff(2)?)(\?[a-z0-9=&.]+)?$/,
            loader: 'url-loader?limit=100000&name=fonts/[name].[ext]'
        }
    ],
    },
    devtool: 'inline-source-map',
    plugins: [
        CSSExtract
    ]
}

我尝试使用file-loader,但出现了相同的问题。
它显示错误:

@font-face {
^
SyntaxError: 无效或意外的令牌

我该如何使用@font-face从node_modules中添加CSS文件?


好的加载字体教程,也许会有所帮助: https://www.chriscourses.com/blog/loading-fonts-webpack - Vasyl Gutnyk
@VasylGutnyk 我几乎按照那篇文章中提到的每一件事情去做了。 - zulqarnain
你们也有 CSS 的加载器吗? - PlayMa256
@PlayMa256,是的,css-loader和sass-loader。 - zulqarnain
@csilk 我已经在使用URL加载器,就像他在答案中展示的那样。 - zulqarnain
1个回答

2

这是webpack的设置:

{
        test: /\.(woff(2)?|ttf|eot)(\?v=\d+\.\d+\.\d+)?$/,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "[name].[contenthash].[ext]",
              outputPath: "fonts/",
            },
          },
        ],
      },

然后您需要将它们导入到CSS或SCSS主文件中。
@font-face {
  font-family: "Montserrat";
  src: url("../../assets/fonts/Montserrat-Light.ttf");
  font-weight: lighter;
  font-style: normal;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接