As you know, in Webpack, you cannot simply substitute a variable as a require() argument. I read a lot of discussions on this topic and, frankly, did not understand how to solve this problem. Specifically, in my case, it is necessary not only to make the require() argument a variable, but also the path, which is the value of the variable, contains an alias (in this example, projectOpenScripts ):

 export default class Resources { constructor(pathToResourcesFile: string){ // true console.log(pathToResourcesFile === 'projectOpenScripts/resources/resources.json5') // works let parsedResources = require('projectOpenScripts/resources/resources.json5'); // does not work let parsedResources = require(pathToResourcesFile); console.log(parsedResources.c) } } 

I use TypeScript , because my aliases are declared not only in webpack.config.js , but also in tsconfig.json :

tsconfig.json

 { "compilerOptions": { // ... "baseUrl": "./", "projectOpenScripts": ["development/1_Source/1_open/3_scripts"] }, "types": [ // Need for require() and require.ensure "webpack-env" ] } } 

In addition to solving this problem, you need to do something with the warning Critical dependency: the request of a dependency is an expression from the TypeScript compiler.

I can not believe that this problem can not be solved. After all, such restrictions as "it is impossible to substitute a variable as the require () argument" contradict the concept of programming.

  • What concepts are you talking about ?? require is syntactic sugar on top of Module._load and a wrapper on Module.require , if we speak in the context of node.js , it is synchronous and caches all modules at the compilation stage, so just in some way, it will not work out in runtime, it does not know where to look for this module, or rather, it tries to find the module in Module._cache and throws the Cannot find module . Use dynamic import - overthesanity
  • @overthesanity, thank you for the explanation! Dynamic import in this case is unpleasant because it gives an additional JavaScript file, which, in order to load, the webpack will create an additional script in the head and asynchronously load it. This is fine in those cases when some functionality needs to be loaded depending on a certain condition, but in my case the load always happens, therefore, the transformation of Data.json into a separate dynamic loadable module is not reasonable. The campaign will have to make the Data.json file itself an argument ... - Gleb Sideways
  • one
    By the way, Я использую TypeScript, потому у меня алиасы объявлены не только в webpack.config.js, но и в tsconfig.json : github.com/dividab/tsconfig-paths-webpack-plugin - Daniel Khoroshko

0