简体   繁体   中英

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!

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.

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. I need to import them with Common.js and export them with 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:

'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:

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. Only if it gets altered again (even if just gets saved again with the same data), the index.js will reflect that change.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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