webpack 网页包未加载@font-face

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

在我的React应用中,我正在实现服务器端渲染,因此出于性能问题,我不想在服务器端添加node_modules。但我希望从node_modules中添加css,它们用作UI工具包libs.so我在我的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工具包文件中加载@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从node_modules添加css文件

ccrfmcuu

ccrfmcuu1#

以下是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;
}

相关问题