文章出處

semantic ui css 的第一行引用了 google web font api,由于不可告人而又眾所周知的原因,這條鏈接在國內無法訪問:

@import url('https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic&subset=latin');

css 是阻塞渲染的,而 css 中的 import 又會進一步阻塞加載和渲染,所以就導致頁面樣式加載十分緩慢。

像 semantic ui 這樣的開源框架,一般使用 npm 或者 bower 安裝,也不好去直接修改源碼。

借助 webpack 的 string-replace-webpack-plugin 可以將這句引用進行替換,從而解決渲染阻塞問題。

以下是相關 webpack.config.js 配置示例,可供參考:

var path = require('path')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var StringReplacePlugin = require('string-replace-webpack-plugin')

module.exports = {
  entry: {
    common: './static/src/global.js'
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'static/global/'),
    publicPath: '/static/global/'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({use: ['css-loader']})
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          use: ['css-loader', 'sass-loader']
        })
      },
      {
        test: /semantic\.css$/,
        loader: StringReplacePlugin.replace({
          replacements: [{
              pattern: /https\:\/\/fonts\.googleapis\.com[^\']+/ig,
              replacement: function (match, p1, offset, string) {
                return 'data:text/css,*{}'
              }
            }]
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('common.css'),
    new StringReplacePlugin()
  ]
}

需要注意的是 webpack v2 中 rule 的結合順序是從后至前、從右至左,所以 semantic.css 復寫的 rule 要放到最后,且不包含其他 loader 設置。

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()