如何在 es6 中缓存 bust 导入的模块? [英] How do I cache bust imported modules in es6?

查看:17
本文介绍了如何在 es6 中缓存 bust 导入的模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES6 模块允许我们像这样创建一个单一的入口点:

//main.js从'foo'导入foo;foo()

<script src="scripts/main.js" type="module"></script>

foo.js 将存储在浏览器缓存中.在我将新版本的 foo.js 推向生产之前,这是可取的.

通常的做法是添加具有唯一 id 的查询字符串参数以强制浏览器获取新版本的 js 文件 (foo.js?cb=1234)

如何使用 es6 模块模式实现这一点?

解决方案

用于救援的 HTTP 标头.使用 ETag 提供您的文件,它是以下各项的校验和文件.S3 在示例中默认情况下会这样做.当您再次尝试导入文件时,浏览器将请求该文件,这次将 ETag 附加到if-none-match" 标头:服务器将验证 ETag 是否与当前文件匹配并发送回 304 Not Modified,从而节省带宽和时间,或文件的新内容(带有新的 ETag).

这样,如果您更改项目中的单个文件,用户就不必下载所有其他模块的完整内容.添加一个简短的 max-age 头也是明智的,这样如果同一模块在短时间内被请求两次,就不会有额外的请求.

如果您添加缓存破坏(例如,通过捆绑程序附加 ?x={randomNumber},或将校验和添加到每个文件名),您将强制用户在每个新项目版本中下载每个必要文件的完整内容.

在这两种情况下,您无论如何都会对每个文件进行请求(级联上导入的文件将产生新请求,如果您使用 etags,至少可能以小 304 结束).为了避免这种情况,您可以使用动态导入 e.g if (userClickedOnSomethingAndINeedToLoadSomeMoreStuff) { import('./someModule').then('...') }

ES6 modules allows us to create a single point of entry like so:

// main.js

import foo from 'foo';

foo()

<script src="scripts/main.js" type="module"></script>

foo.js will be stored in the browser cache. This is desirable until I push a new version of foo.js to production.

It is common practice to add a query string param with a unique id to force the browser to fetch a new version of a js file (foo.js?cb=1234)

How can this be achieved using the es6 module pattern?

解决方案

HTTP headers to the rescue. Serve your files with an ETag that is the checksum of the file. S3 does that by default at example. When you try to import the file again, the browser will request the file, this time attaching the ETag to a "if-none-match" header: the server will verify if the ETag matches the current file and send back either a 304 Not Modified, saving bandwith and time, or the new content of the file (with its new ETag).

This way if you change a single file in your project the user will not have to download the full content of every other module. It would be wise to add a short max-age header too, so that if the same module is requested twice in a short time there won't be additional requests.

If you add cache busting (e.g. appending ?x={randomNumber} through a bundler, or adding the checksum to every file name) you will force the user to download the full content of every necessary file at every new project version.

In both scenario you are going to do a request for each file anyway (the imported files on cascade will produce new requests, which at least may end in small 304 if you use etags). To avoid that you can use dynamic imports e.g if (userClickedOnSomethingAndINeedToLoadSomeMoreStuff) { import('./someModule').then('...') }

这篇关于如何在 es6 中缓存 bust 导入的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆