webpack指紋策略以及多頁面配置

1、指紋策略

瀏覽器緩存機(jī)制:
第一次進(jìn)入頁面,會查看是否有換緩存,如果無知進(jìn)行請求。并緩存放回回來的頁面。

第二次進(jìn)入頁面,會直接顯示已緩存的頁面。

問題:文件已經(jīng)上傳的服務(wù)器了,但是頁面并沒有更新。

這個時(shí)候需要使用指紋策略
1、hash:當(dāng)文件內(nèi)容發(fā)生變化時(shí),打包的文件名才會改變。作用范圍最大,作用于整個工程。
使用方法如下:

image.png

查看打包后的文件:
image.png

講文件名轉(zhuǎn)化成hash,同時(shí)直截取前六位。

問題:假如我們是多入口文件,如果項(xiàng)目中有一個js文件進(jìn)行了修改,那么整個項(xiàng)目的js文件名都會被修改,這就不合理。
image.png

chunkhash:只打包修改文件內(nèi)容有改變的文件。影響訪問時(shí)一個chunks。


image.png
問題:假如我們js文件中引用了css文件,使用的是chunkhash,當(dāng)css文件發(fā)生變化時(shí),也會改變引入的js文件的hash變化。這就不合理。

contenthash:自身內(nèi)容更新,hash才會更新。


image.png

cdn就是分布式服務(wù)器。
訪問時(shí)采用就近原則,例如:上海用戶訪問就采用上海節(jié)點(diǎn),深證用戶訪問就采用深圳節(jié)點(diǎn)

2、如何打包配置多頁面

1、entry配置:

  entry: {
    index: "./src/index.js",
    list: "./src/list.js",
  },

2、plugins配置:
默認(rèn)配置:

plugins: [
    new htmlWebpackPlugin({
      template: "./src/index.html",
      filename: "index.html",
      chunks: ["index"],
    }),
    new htmlWebpackPlugin({
      template: "./src/list.html",
      filename: "list.html",
      chunks: ["list"],
    }),
  ],

動態(tài)配置:
1、需要規(guī)定好所有多頁面文件下的目錄如下:都有index.js和index.html文件。


image.png

2、npm isntall glob -D 安裝glob。可以幫助我們用通配的方式找到符合目錄。
3、再webpack.config.js中代碼編寫。

const setMpa = () => {
  const entry = {};
  const htmlwebpackplugins = [];

    //找到符合頁面的文件
  const entryFiles = glob.sync(path.join(__dirname, "./src/*/index.js"));

  entryFiles.map((item, index) => {
    const entryFile = entryFiles[index];
    const match = entryFile.match(/src\/(.*)\/index\.js$/);
    const pageName = match[1]; //  獲取到key
    entry[pageName] = entryFile;
    htmlwebpackplugins.push(
      new htmlWebpackPlugin({
        template: `./src/${pageName}/index.html`,
        filename: `${pageName}.html`,
        chunks: [pageName],
      })
    );
  });

  return {
    entry,
    htmlwebpackplugins,
  };
};
const { entry, htmlwebpackplugins } = setMpa();

entry配置:


image.png

plugin配置:


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容