How to preload Google Fonts from CDN with webpack

孤者浪人 提交于 2019-12-11 14:56:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!