【发布时间】:2020-01-04 15:04:10
【问题描述】:
虽然这个问题与 Workbox 和 Webpack 有关,但它不需要任何库的先验知识。
背景(不熟悉 Workbox 可跳过)
我目前正在使用 Workbox 4.3.1 (workbox-webpack-plugin) 中的 InjectManifest 插件。这个版本的库提供了一个名为 manifestTransforms 的选项,但不幸的是,转换不会应用于 webpack 编译中的资产(这是一个 known issue)。
虽然这已在 Workbox v5+ 中修复,但由于我的构建过程中的另一个库需要 webpack v3 (Dynamic Importing in Laravel Mix),我无法升级
我之所以提到上面的原因是因为不幸的是解决方案不是升级到workbox v5+。
问题
我有一个自动生成的文件,如下所示:
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "68cd3870a6400d76a16c",
"url": "//css/app.css"
},
// etc...
]);
我需要以某种方式提取存储在self.__precacheManifest 中的对象的内容,应用我自己的转换,然后将其保存回文件中。
我尝试过的...
据我所知:
// As the precached filename is hashed, we need to read the
// directory in order to find the filename. Assuming there
// are no other files called `precache-manifest`, we can assume
// it is the first value in the filtered array. There is no
// need to test if [0] has a value because if it doesn't
// this needs to throw an error
let manifest = fs
.readdirSync(path.normalize(`${__dirname}/dist/js`))
.filter(filename => filename.startsWith('precache-manifest'))[0];
require('./dist/js/' + manifest);
// This does not fire because of thrown error...
console.log(self.__precacheManifest);
这会引发以下错误:
自我没有定义
我明白它为什么会抛出错误,但我不知道如何解决这个问题,因为我需要以某种方式读取文件的内容才能提取对象。有人可以在这里给我建议吗?
请记住,一旦我对对象应用了转换,我就需要将更新后的对象保存到文件中...
【问题讨论】:
-
你的 js 脚本中应该有什么
self? -
@ChrisRollins -
self将引用window,因为预缓存文件仅用于客户端。我无法控制预缓存文件的初始内容,它是由InjectManifest插件自动生成的 -
如果我错了请纠正我,但我认为你想要
this -
@ChrisRollins - 如前所述,我无法控制该文件,它是由插件自动生成的。
self与this不同。见这里:stackoverflow.com/questions/16875767/… -
哦,我的错,我看到您实际上是在使用
require运行生成的脚本,所以问题是您运行的代码仅适用于节点中的浏览器。也许只是在require声明之前将self绑定到全局对象
标签: javascript node.js webpack fs workbox