如何使用 Node.js 在非常简单的 JS 文件中编辑对象

How to edit an object within a very simple JS file using Node.js

虽然这个问题与 Workbox 和 Webpack 有关,但不需要任何库的先验知识。

背景介绍(不熟悉Workbox的请跳过)

我目前正在使用 Workbox 4.3.1 (workbox-webpack-plugin). This version of the library offers an option called manifestTransforms, but unfortunately, the transformations are not applied to assets within the webpack compilation (this is a known issue) 中的 InjectManifest 插件。

虽然此问题已在 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);

这将引发以下错误:

self is not defined

我明白它为什么会抛出错误,但我不知道如何解决这个问题,因为我需要以某种方式读取文件的内容以提取对象。有人可以在这里给我建议吗?

请记住,一旦我对对象应用了转换,我就需要将更新后的对象保存到文件中...

因为 self 指的是 windowwindow 不存在于 node.js 中,因此需要一种解决方法。 应该起作用的一件事是在 Node 的全局范围内定义变量 self 并让 require 语句填充变量的内容,如下所示:

global['self'] = {};
require('./dist/js/' + manifest);
console.log(self.__precacheManifest);

将修改后的内容保存回文件

const newPrecacheManifest = JSON.stringify(updatedArray);
fs.writeFileSync('./dist/js/' + manifest, `self.__precacheManifest = (self.__precacheManifest || []).concat(${newPrecachedManifes});`, 'utf8');