繁体   English   中英

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

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

尽管此问题与Workbox和Webpack有关,但它不需要任何一个库的任何先验知识。

背景(如果不熟悉Workbox,请跳过)

我目前正在使用Workbox 4.3.1中的InjectManifest插件(workbox -webpack-plugin )。 该版本的库提供了一个称为manifestTransforms的选项,但是不幸的是,这些转换未应用于webpack编译中的资产(这是一个已知问题 )。

尽管此问题已在Workbox v5 +中修复,但由于构建过程中需要使用webpack v3( 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是指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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM