In my Webpack application, I have a collection of JSON files that I need to import. These files are named 0.json
, 1.json
, 2.json
, and so on, and can be found in the directory src/res/level/
. However, when I attempt to use require()
to load them into my code, it doesn't seem to work:
private loadWorld() {
// Load the level
// Create a duplicate object to prevent modifications to the original instance created by json-loader
this.state.level = JSON.parse(JSON.stringify(require(`@res/level/${this.level}.json`))) as LevelData;
// ...
}
Every time I run this method, an error is thrown:
Error: Cannot find module "@res/level/1.json". at webpackContextResolve (webpack-internal:///9:16:11) at webpackContext (webpack-internal:///9:9:11)
I'm struggling to understand why this error is occurring. What's even more perplexing is that if I make changes to this line of code before executing the program while running Webpack in watch mode, the JSON files suddenly load without any issues.
I have properly set up an alias for @res
:
resolve: {
extensions: [".ts", ".js", ".glsl", ".json"],
alias: {
"@res": path.join(__dirname, "src/res"),
"@lib": path.join(__dirname, "src/lib"),
"@shader": path.join(__dirname, "src/shader"),
"@control": path.join(__dirname, "src/control"),
"@scene": path.join(__dirname, "src/scene"),
"@util": path.join(__dirname, "src/util"),
}
}
Since this is Webpack 4, I haven't included a loader specifically for JSON files. So, what could be causing this issue?
Furthermore, upon inspecting the generated code, I noticed the following: https://i.sstatic.net/h6gRs.png
This discovery indicates that the JSON files are being loaded, but not from the expected directory.