webpack優化-速度優化-hard-source-webpack-plugin


1、背景

      在項目實現的過程中,想在代碼更改的同時,查看效果的改變,而這個時候長時間的編譯等待,造成了額外的時間浪費。

2、簡介

   HardSourceWebpackPlugin是webpack的插件,為模塊提供中間緩存步驟。為了查看結果,您需要使用此插件運行webpack兩次:第一次構建將花費正常的時間。第二次構建將顯着加快(大概提升90%的構建速度)。

3、實現

       用npm install --save-dev hard-source-webpack-plugin或安裝yarn add --dev hard-source-webpack-plugin。並在webpack的插件配置中添加此插件。

const HardSourceWebpackPlugin = require('hard-source-webpack-plugin')
new HardSourceWebpackPlugin({
    // cacheDirectory是在高速緩存寫入。默認情況下,將緩存存儲在node_modules下的目錄中,因此如 
    // 果清除了node_modules,則緩存也是如此
    cacheDirectory: 'node_modules/.cache/hard-source/[confighash]',
    // Either an absolute path or relative to webpack's options.context.
    // Sets webpack's recordsPath if not already set.
    recordsPath: 'node_modules/.cache/hard-source/[confighash]/records.json',
    // configHash在啟動webpack實例時轉換webpack配置,並用於cacheDirectory為不同的webpack配 
    // 置構建不同的緩存
    configHash: function(webpackConfig) {
       // node-object-hash on npm can be used to build this.
       return require('node-object-hash')({sort: false}).hash(webpackConfig);
    },
    // 當加載器,插件,其他構建時腳本或其他動態依賴項發生更改時,hard-source需要替換緩存以確保輸 
    // 出正確。environmentHash被用來確定這一點。如果散列與先前的構建不同,則將使用新的緩存
    environmentHash: {
       root: process.cwd(),
       directories: [],
       files: ['package-lock.json', 'yarn.lock'],
    },
})

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM