How to preload Google Fonts from CDN with webpack

2019-08-20 11:34发布

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:

enter image description here

Compare to the request utilizing @font-face in the .scss file, get the fonts which I download to local then serve by myself:

enter image description here

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:

enter image description here

  • Local:

enter image description here

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条回答
做个烂人
2楼-- · 2019-08-20 12:07

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.

查看更多
登录 后发表回答