首页 > 解决方案 > 无法访问@font-face 中提到的字体文件

问题描述

首先,我是 webpack 及其加载器的新手。我有一个应用程序,我在其中生成一个 CSS 文件,该文件位于与请求发起的不同域中(更像是静态代码存储库)。问题是,服务器加载 style.css 文件,并且它具有字体的导入,这些字体也存储在同一个存储库中,并且可以通过以下方式访问:

@font-face {
    font-family: someFont;
    src: url(/0.0.1/fonts/f9c391f982c59a955bb0e1866fbbed4a.woff2) format("woff2"),url(/0.0.1/fonts/ac4b1e27ea3661e299554aaa429e97c5.woff) format("woff");
    font-weight: 300;
    font-style: normal;
    font-display:swap}

所以现在,假设这是在styles.less文件内部和域上https://example.com

因为我知道 CORS 问题并在我的节点/Express 应用程序中添加了 cors(),所以这个 style.less 正在完美加载

cont cors = require('cors');
app.use(cors());

现在的问题是,当 style.css 文件尝试加载字体时,我开始收到 CORS 错误。当我检查标头时,所有其他进入该存储库的请求access-control-allow-origin: '*'在响应标头中都有,但在字体请求中没有

这是加载器和路径的 webpack 配置:

output: {
        path: path.resolve(__dirname, `dist/client/${pkg.version}`),
        publicPath: `/${pkg.version}/`
    },

    devtool: ifProduction('nosources-source-map', 'source-map'),
module: {
        rules: [
            {
                test: /\.less$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader']
            },
            {
                test: /\.(ttf|eot|svg?)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'file-loader?name=fonts/[name].[ext]'
            },
            {
                test: /\.(png|jpg|ico|svg|eot|ttf|woff|woff2)$/,
                loader: 'url-loader'
            }
        ]
    },

有人可以帮我解决这可能有什么问题吗?

标签: javascriptcssreactjswebpackfont-face

解决方案


尝试将url字符串包含font-face在引号中的定义中。如下所示。

// Note the quotation marks

src: url("/0.0.1/fonts/f9c391f982c59a955bb0e1866fbbed4a.woff2") format("woff2"),
     url("/0.0.1/fonts/ac4b1e27ea3661e299554aaa429e97c5.woff") format("woff");


推荐阅读