[英]How can I automatically update my javascript file to import newly detected files?
I tagged watchman as it MIGHT be the solution I'm looking for, but I don't quite know how to use it in this way! 我将watchman标记为它可能是我正在寻找的解决方案,但是我不太了解如何以这种方式使用它!
I have a directory 我有一个目录
/imgs
/icons
/bird.png
/cat.png
/dog.png
/pig.png
and I have a file 我有一个文件
/imgs/index.js
My index.js is responsible for importing all of the images and then exporting a single object for the rest of my project to use. 我的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;
What I want to do is watch my imgs folder for new additions, and automatically update my index.js to import these new files and add them to my object. 我想要做的是观察imgs文件夹中是否有新添加的内容,并自动更新我的index.js以导入这些新文件并将它们添加到我的对象中。 I need to import them with Common.js and export them with ES6.
我需要使用Common.js导入它们,并使用ES6导出它们。
Does anyone know a good solution to this problem? 有谁知道这个问题的好解决方案?
A potential solution is to write a JavaScript script that generates your index.js like so: 潜在的解决方案是编写一个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');
});
});
Place that file (let's call it watcher.js for this purpose) in imgs
's parent directory and make watchman run it whenever changes in your icons directory are detected: 将该文件(为此目的将其称为watcher.js)放置在
imgs
的父目录中,并让imgs
在检测到图标目录中的更改时运行它:
watchman imgs/icons "node watcher.js"
Notice that if a new file gets put into the watched directory, the index.js-creating script will not re-run. 请注意,如果将新文件放入监视的目录,则不会重新运行创建index.js的脚本。 Only if it gets altered again (even if just gets saved again with the same data), the index.js will reflect that change.
仅当再次更改(即使只是使用相同的数据再次保存)时,index.js才会反映该更改。
You can simply test that by running touch imgs/icons/crabigator.png
twice and look at the watchman log and/or content of index.js. 您只需运行两次
touch imgs/icons/crabigator.png
并查看值班日志和/或index.js的内容,即可对其进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.