问题
My goal is importing 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 deploy my bundle, the google fonts is applied, and the fonts request is like this:
Compare to the request utilizing @font-face
in the .scss
file, get the fonts which I download to local then serve 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 to 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!!
回答1:
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.
来源:https://stackoverflow.com/questions/56632884/how-to-preload-google-fonts-from-cdn-with-webpack