如何使用 webpack 从 CDN 预加载 Google 字体 [英] How to preload Google Fonts from CDN with webpack
问题描述
我的目标是通过以下方式导入字体:
@import url('https://fonts.googleapis.com/css?family=Poppins:i,100,200,300);
在我的 .scss
文件中,然后通过
对比在.scss
文件中使用@font-face
的请求,将字体下载到本地然后自己提供:
只有第二个的文件名跟在我在file-loader
配置中定义的name
之后:
exports.font = {测试:/\.(woff|woff2|ttf|eot)$/,加载器:'文件加载器',询问: {name: '[name]-[hash:6].[ext]',},};
这对我来说还是合理的,所以我的猜测是,我认为 Webpack 在创建依赖关系图时 css-loader
解释了 @import
和 url()
,然后 file-loader
将文件复制到我们的 dist 文件夹,但如果源来自外部,file-loader
将无法处理.><小时>
再次比较 CDN 和本地的请求,Devtool 中的 Sources 部分向我展示了:
- CDN:
- 本地:
当我从 CDN 请求字体时,有一个新文件夹 gstatic,然后我添加 preload-webpack-plugin,当我添加preload-webpack-plugin,仅在向本地发送字体请求的方式中预加载字体.
exports.preloadWebpack = new PreloadWebpackPlugin({rel: '预加载',包括:'allAssets',文件白名单:[/\.woff/,/\.woff2/,/\.ttf/],如:'字体',});
感谢任何帮助!
您可以考虑使用:Google Fonts Webpack Plugin,
并以这种方式使用 npm 安装它:
npm install @beyonk/google-fonts-webpack-plugin
更多信息.
My goal is to import the fonts by:
@import url('https://fonts.googleapis.com/css?family=Poppins:i,100,200,300);
in my .scss
file, then preload all the fonts by preload-webpack-plugin
After I deployed my bundle, the google fonts are applied, and the font request is like this:
Compare to the request which utilized @font-face
in the .scss
file, get the fonts downloaded to local then served by myself:
Only the file name of second one follows the name
I defined in file-loader
configuration:
exports.font = {
test: /\.(woff|woff2|ttf|eot)$/,
loader: 'file-loader',
query: {
name: '[name]-[hash:6].[ext]',
},
};
It's still reasonable for me, so my guess is, I think when Webpack is creating Dependency Graph css-loader
interprets @import
and url()
, then file-loader
duplicates the files to our dist folder, but if the source is from external, file-loader
won't work on that.
Again, compare requests to CDN and local, the Sources section in Devtool shows me:
- CDN:
- Local:
When I request fonts from CDN there is a new folder gstatic, before I add preload-webpack-plugin, the fonts are requested dynamically when meet the new fonts family/style in the new pages, after I add preload-webpack-plugin, the fonts are preloaded only for the way which is sending fonts request to local.
exports.preloadWebpack = new PreloadWebpackPlugin({
rel: 'preload',
include: 'allAssets',
fileWhitelist: [/\.woff/, /\.woff2/, /\.ttf/],
as: 'font',
});
Any help is appreciated!!
You could consider using: Google Fonts Webpack Plugin,
and install it using npm in this way:
npm install @beyonk/google-fonts-webpack-plugin
More info.
这篇关于如何使用 webpack 从 CDN 预加载 Google 字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!