2

When I pass a string to file-loader require method in computed property it works fine, like this

computedProp () {
  return require('../path/to/file');
}

but if I try to pass some variable into it it throws error

computedProp () {
  const l = '../path/to/file';
  return require(l);
}

Error: Error: Cannot find module "."

How can I fix that? I want to create the relative path based on some condition and then want to pass it to require method to get an absolute path.

coure2011
  • 40,286
  • 83
  • 216
  • 349

1 Answers1

3

Very similar answers had been posted in Stack:

Since Webpack is running in build-time, it can't figure out which modules to bundle when the name is a dynamic variable. You can give it hints by specifying part of the path (for example, if you know all the modules are in a single directory).

Using require('...') with a variable vs. using a string in webpack

So, for that to work you could test:

computedProp () {
  const path = '../path/to'
  const file = 'file';
  return require(path + '/' + file);
}

More info Here and Here

Hope it helps.

Gerardo Rosciano
  • 901
  • 5
  • 11