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.
requireis syntactic sugar on top ofModule._loadand a wrapper onModule.require, if we speak in the context ofnode.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 inModule._cacheand throws theCannot find module. Use dynamicimport- overthesanityЯ использую TypeScript, потому у меня алиасы объявлены не только в webpack.config.js, но и в tsconfig.json: github.com/dividab/tsconfig-paths-webpack-plugin - Daniel Khoroshko