Nicolas S.Xu
Nicolas S.Xu

Reputation: 14554

webpack require fails if file path using string variable concat

I've been encountering strange webpack require problem. If I use variable in require string, it fails to load anything but no error message. But use full path string will succeed in loading. Do you know what is going on?

var _commonFolder = '../Presentation/Base/Default/js/source/_common/'
require(_commonFolder + 'docReady.js');
// the above require will fail to load anything, but no error message


require('../Presentation/Base/Default/js/source/_common/docReady.js');
// the above require successfully load the content

Upvotes: 2

Views: 888

Answers (1)

Ayush Nawani
Ayush Nawani

Reputation: 664

I guess, what you are try to do comes under dynamic requires of a file .

Read webpack documentation explaining dynamic requires.

var _commonFolder = '../Presentation/Base/Default/js/source/_common/'
require(_commonFolder + 'docReady.js');

Here, docReady.js will not get bundled as require contains expression _commonFolder + 'docReady.jsand that can't be resolved by webpack while compiling and bundling .

On getting expression inside require like in your case , webpack may create a context in your bundled output file.

whereas

require('../Presentation/Base/Default/js/source/_common/docReady.js');

will bundle docReady.js by webpack as you are providing complete relative path

Upvotes: 3

Related Questions