webpack指纹策略以及多页面配置

1、指纹策略

浏览器缓存机制:
第一次进入页面,会查看是否有换缓存,如果无知进行请求。并缓存放回回来的页面。

第二次进入页面,会直接显示已缓存的页面。

问题:文件已经上传的服务器了,但是页面并没有更新。

这个时候需要使用指纹策略
1、hash:当文件内容发生变化时,打包的文件名才会改变。作用范围最大,作用于整个工程。
使用方法如下:

image.png

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

讲文件名转化成hash,同时直截取前六位。

问题:假如我们是多入口文件,如果项目中有一个js文件进行了修改,那么整个项目的js文件名都会被修改,这就不合理。
image.png

chunkhash:只打包修改文件内容有改变的文件。影响访问时一个chunks。


image.png
问题:假如我们js文件中引用了css文件,使用的是chunkhash,当css文件发生变化时,也会改变引入的js文件的hash变化。这就不合理。

contenthash:自身内容更新,hash才会更新。


image.png

cdn就是分布式服务器。
访问时采用就近原则,例如:上海用户访问就采用上海节点,深证用户访问就采用深圳节点

2、如何打包配置多页面

1、entry配置:

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

2、plugins配置:
默认配置:

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

动态配置:
1、需要规定好所有多页面文件下的目录如下:都有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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容