![](/img/trans.png)
[英]How to retrieve an object from node.js using JSON.stringify() within a javascript file?
[英]How to edit an object within a very simple JS file using Node.js
盡管此問題與Workbox和Webpack有關,但它不需要任何一個庫的任何先驗知識。
我目前正在使用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
是指window
和window
在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.