Webpack chunk的url增加查询字符串

209 阅读1分钟

第一次写文章,分享一点 baidu 得不到的东西。

遇到的问题

使用Webpack做SPA项目,项目稍微大了之后,大家都会想到按需加载,比如 React 使用 React.Lazy 。然后我们的 webpack.config.js 这样写:

module.export = {
  output: {
    path: "dist",
    filename: "[name].[contenthash:6].js",
    chunkFilename: "[name]-chunk.[contenthash:6].js",
  },
}

最后浏览器里我们的加载url可能就变成了这样的:
入口文件 https://site.example.com/static/js/index.f67ab1.js
chunk文件 https://site.example.com/static/js/settings-chunk.af21e1.js

入口文件是通过 HtmlWebpackPlugin 挂载到 html 上的,入口文件已经做到随意配置querystring了,但是 chunk 文件是动态加载的,也想把它改成如下:
https://site.example.com/static/js/settings-chunk.af21e1.js?h=[某动态参数]

解决方案

// 解决 js 文件 querystring 问题
// eslint-disable-next-line prefer-const, no-var
declare var __webpack_get_script_filename__: (chunkId: string) => string; // NOSONAR
const oldFn = __webpack_get_script_filename__;
__webpack_get_script_filename__ = (chunkId) => {
  const filename = oldFn(chunkId);
  if (filename.includes("?")) {
    return filename + `&ts=${Date.now()}`;
  }
  return filename + `?ts=${Date.now()}`;
};

// 解决 css 文件 querystring 问题
declare namespace __webpack_require__ {
  // eslint-disable-next-line prefer-const, no-var
  var miniCssF: (chunkId: string) => string; // NOSONAR
}
const oldMiniCssF = __webpack_require__.miniCssF;
__webpack_require__.miniCssF = (chunkId) => {
  const filename = oldMiniCssF(chunkId);
  if (filename.includes("?")) {
    return filename + `&ts=${Date.now()}`;
  }
  return filename + `?ts=${Date.now()}`;
};

嘿嘿嘿

chunk js文件的方法,百度能搜到,但是chunk css 文件的方法,百度没搜到,拿去用吧。如果还是没生效,那就换个位置写一下,比如:

import { somethingA } from './something-a';

// 解决 js 文件 querystring 问题
// eslint-disable-next-line prefer-const, no-var
declare var __webpack_get_script_filename__: (chunkId: string) => string; // NOSONAR
const oldFn = __webpack_get_script_filename__;
__webpack_get_script_filename__ = (chunkId) => {
  const filename = oldFn(chunkId);
  if (filename.includes("?")) {
    return filename + `&ts=${Date.now()}`;
  }
  return filename + `?ts=${Date.now()}`;
};

// 解决 css 文件 querystring 问题
declare namespace __webpack_require__ {
  // eslint-disable-next-line prefer-const, no-var
  var miniCssF: (chunkId: string) => string; // NOSONAR
}
const oldMiniCssF = __webpack_require__.miniCssF;
__webpack_require__.miniCssF = (chunkId) => {
  const filename = oldMiniCssF(chunkId);
  if (filename.includes("?")) {
    return filename + `&ts=${Date.now()}`;
  }
  return filename + `?ts=${Date.now()}`;
};

if (somethingA()) {
  import('../other-theme.less');
}

课后作业

__webpack_require__.miniCssF 是哪个plugin暴露出来的方法呢? 嗯~ o( ̄▽ ̄)o