Ropenfold
Ropenfold

Reputation: 199

fixing an eslint error - Calls to require() should use string literals

I am correcting some errors which are eslint related and I am getting the following errors:

enter image description here

const requireFiles = (directory, app) => {
   fs.readdirSync(directory).forEach(fileName => {
  if (fs.lstatSync(`${directory}/${fileName}`).isDirectory()) {
  requireFiles(`${directory}/${fileName}`, app);
  return;
  }
  // Skip this file
  if (fileName === 'index.js' && directory === __dirname) return;
  // Skip unknown filetypes
  if (validFileTypes.indexOf(fileName.split('.').pop()) === -1) return;
  // Require the file.
  const path = `${directory}/${fileName}`;
  const module = require(path).default;
  global.logger.logInfo('-requiring : ', path);
  if (module.init) {
     module.init(app);
     global.logger.logInfo('-initing : ', path);
    }
 });
};

How I understand this it is asking for a string but I creating this in the line above, is there a better way of doing this?

Upvotes: 1

Views: 3364

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

How I understand this it is asking for a string but I creating this in the line above

A string is not a string literal. A string literal is an expression starting with " or ' and ending with a matching one of those, "like this" 'or this'. You're using strings with require, but not string literals. The point of the restriction is that string literals can be statically analyzed. Strings created dynamically can't be.

If you want to use strings created dynamically (like the ones in the code you've shown), you'll have to turn off that ESLint rule. Using dynamic strings with require is fine in (say) Node.js. It's a problem when you're trying to use bundlers like Webpack or Rollup (because they need to statically analyze the module structure)l.

Upvotes: 1

Related Questions