如何在 Rollup.js 中进行缓存破坏?

Geo*_*nig 5 javascript browser-cache rollupjs

我的项目中,我需要做缓存破坏,因为在新部署之后,浏览器通常只重新加载 HTML 而不是 JS 和 CSS 文件。

目前,我没有以任何方式构建 HTML,它只是已经位于公共目录中。

最简单的方法似乎是在 JS 引用中添加时间戳:

<script type="module" src="bundle/index.js?ts=20201026-102300"></script>
Run Code Online (Sandbox Code Playgroud)

现在,在已经使用rollup.js的项目中实现这一目标的最佳方法是什么?

我见过@rollup/plugin-html,但我对其文档中的示例感到困惑,因为它需要一个 JS 文件作为输入:

 input: 'src/index.js',
Run Code Online (Sandbox Code Playgroud)

那应该是什么JS文件?

相反,我希望需要定义

  • 一个输入 HTML 文件
  • 一些代码空间来设置时间戳变量
  • 输出 HTML 文件

那么最好的方法是什么,是使用@rollup/plugin-html还是其他方法?

Rob*_*len 0

我自己来到这里寻找这个问题的答案,过了一会儿,经过一些正则表达式的摆弄,我就让它工作了。

注意:此解决方案会在您每次构建 HTML 文件时对其进行编辑。没有输入(模板)HTML 和输出 HTML。

  1. 安装rollup-plugin-replace-html-vars

npm install rollup-plugin-replace-html-vars --save-dev

  1. 将这段配置添加到您的rollup.config.js文件中
// rollup.config.js
// ...
plugins: [
    replaceHtmlVars({
        files: '**/index.html',
        from: /\.\/\w+\/\w+\.\w+.\w+\?v=\d+/g,
        to: './dist/app.min.js?v=' + Date.now(),
    }),
]

Run Code Online (Sandbox Code Playgroud)
  1. 在您的 中index.html,将此引用添加到app.js
<script type="module" src="./dist/app.min.js?v=1630086943272"></script>
Run Code Online (Sandbox Code Playgroud)
  1. 运行 rollup ,每次运行时,index.html 中对 app.js 的引用都会有一个构建时间的时间戳。

奖金:

如果您的文件名中没有 a .min,请使用此正则表达式:

// rollup.config.js
// ...
plugins: [
    replaceHtmlVars({
        files: '**/index.html',
        from: /\.\/\w+\/\w+\.\w+.\w+\?v=\d+/g,
        to: './dist/app.min.js?v=' + Date.now(),
    }),
]

Run Code Online (Sandbox Code Playgroud)

全面披露; 我不是正则表达式向导,只是设法将其破解在一起。我敢打赌这里有人会有更好的方法来./dist/app.min.js?v=1630086943272使用正则表达式进行捕获,但这适用于我的解决方案。