如何自动更新javascript文件以导入新检测到的文件?
我标记了watchman,因为它可能是我正在寻找的解决方案,但我不太知道如何以这种方式使用它 我有一个目录如何自动更新javascript文件以导入新检测到的文件?,javascript,reactjs,ecmascript-6,watchman,Javascript,Reactjs,Ecmascript 6,Watchman,我标记了watchman,因为它可能是我正在寻找的解决方案,但我不太知道如何以这种方式使用它 我有一个目录 /imgs /icons /bird.png /cat.png /dog.png /pig.png 我有一份档案 /imgs/index.js My index.js负责导入所有图像,然后导出单个对象供项目的其余部分使用 const bird = require('./icons/bird.png'); const
/imgs
/icons
/bird.png
/cat.png
/dog.png
/pig.png
我有一份档案
/imgs/index.js
My index.js负责导入所有图像,然后导出单个对象供项目的其余部分使用
const bird = require('./icons/bird.png');
const cat = require('./icons/cat.png');
const dog = require('./icons/dog.png');
const pig = require('./icons/pig.png');
const Icons = { bird, cat, dog, pig };
export default Icons;
我想做的是监视我的imgs文件夹中的新添加内容,并自动更新我的index.js以导入这些新文件并将它们添加到我的对象中。我需要用Common.js导入它们,然后用ES6导出它们
有人知道这个问题的好解决方案吗?一个潜在的解决方案是编写一个JavaScript脚本来生成index.js,如下所示:
'use strict';
const fs = require('fs');
const DIR = __dirname + '/imgs/icons';
const output = __dirname + '/imgs/index.js';
return fs.readdir(DIR, (err, files) => {
let result = '';
let references = [];
files.forEach(item => {
// assuming item has the format animal.png
let newReference = item.split('.')[0];
references.push(newReference);
result += `const ${newReference} = require('./icons/${item}');\n`;
});
result += `\nconst Icons = { ${references} };\n\nexport default Icons;`;
fs.writeFile(output, result, err => {
if (err) throw err;
console.log(output + ' updated');
});
});
将该文件放在imgs的父目录中,我们将其命名为watcher.js,并在检测到icons目录中的更改时让watchman运行该文件:
watchman imgs/icons节点watcher.js
请注意,如果将新文件放入监视的目录中,index.js-creating脚本将不会重新运行。只有当它再次被修改时,即使只是使用相同的数据再次保存,index.js才会反映该修改
您只需运行两次touch imgs/icons/crabigator.png并查看watchman日志和/或index.js的内容即可测试这一点。谢谢,这正是我想要的!