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

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

问题描述

ES6模块使我们可以像这样创建单个入口点:

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 将存储在浏览器缓存中。在我将新版本的 foo.js 投入生产之前,这是理想的。

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

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

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)

如何使用es6模块模式来实现?

How can this be achieved using the es6 module pattern?

推荐答案

用于救援的HTTP标头。使用 ETag 为文件提供服务文件。例如,S3会默认情况下
当您尝试再次导入文件时,浏览器将请求文件,这次将ETag附加到 if-none-match 标头:服务器将验证ETag是否与当前文件匹配,并发送回304 Not Modified,保存带宽和时间,或文件的新内容(带有新的ETag)。

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).

这样,如果您在项目中更改单个文件,则用户不必下载所有其他模块的全部内容。最好添加一个简短的 max-age 头,这样,如果在短时间内两次请求相同的模块,就不会有其他请求。

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.

如果您添加缓存清除(例如,通过捆绑程序添加?x = {randomNumber},或将校验和添加到每个文件名),则将迫使用户下载全部内容

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.

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

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中缓存导入的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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