Error: Webpack 4 - Unable to locate JSON module

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.

Answer №1

By changing my method to use string concatenation instead of a template string, the compiler started loading the JSON files in a consistent manner:

this.state.level = JSON.parse(JSON.stringify(require("@res/level/" + this.level.toString() + ".json"))) as LevelData;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to fetch valid JSON from a different domain using JQuery and AJAX

I'm having trouble accessing a JSON api from a specific adult-themed website. I've been trying to make it work but so far no luck. You can find my code snippet in this jsfiddle: http://jsfiddle.net/SSqwd/ and here is the script: $.ajax({url: &ap ...

Adjust the color of an SVG upon clicking a button using TypeScript

I am looking to dynamically change the fill color of my SVG when a button is clicked. While I have been successful in changing it through external CSS using the npm package angular-svg-icon, I am unsure how to achieve this using TypeScript. I came across a ...

What is the process for converting a multidimensional array from PHP into JavaScript?

Recently, I've been experimenting with dygraph. To populate my graph, I fetch data via an ajax call and then need to convert the returned JSON array into a JavaScript array. My dygraph options are set up like this: series = { sample1: { ...

Unable to modify state upon submission of a form

I am facing an issue where I need to update the state on the main page, but the values are updated three levels down... This particular component is responsible for fetching all the cities, storing the data in the State, and then mapping through the citie ...

The MetadataRoute.Sitemap in NextJs is missing a definition for alternates

The issue at hand My current task involves generating a sitemap with hreflang links for different languages. Following the guidelines provided in the NextJs documentation (https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap#generat ...

Retrieving JSON information from a URI in PHP without relying on cURL

Recently, I encountered a scenario where I needed to retrieve data from a URI returned in JSON format on my IIS machine with PHP. The specific URL was: The challenge was that I couldn't utilize cURL for this task. Is there an alternate method to acco ...

Guide to sending a body containing formData inside a key using the fetch API

Whenever I attempt to send an image and a path to the API, it is being sent as [object Object] export async function uploadImageToCDN(image: FormData, directory: string = 'dir'): Promise<any> { const token = await authorizeInApi() const he ...

Encountering challenges with synchronous calls in AngularJS

Two service calls need to be executed synchronously in a specific order, using promises. However, the execution is not happening as intended. Controller: vm.nominationSVC.zipping(vm.fileSelected, vm.selectedCategoryId). then(function (respons ...

AmCharts 4: defining the grid interval

I am currently working on creating a polar chart to showcase Satellite data. https://i.sstatic.net/DNUZ1.jpg However, I am facing a challenge with setting the grid size to be displayed in increments of 45 degrees. Despite trying various amcharts 4 functi ...

TypeScript powering the Bundler

A few versions back, TypeScript exposed the customTransformer API in its API. I am interested in developing a transformer that can handle import statements (and maybe requires as well) in order to resolve bundle dependencies, similar to how webpack, brows ...

Having trouble getting JSX to compile while running tests with Jasmine and PhantomJS

When attempting to write a test that includes a rendering of a component using react/jasmine/phantomjs, I encountered an issue. My approach was as follows: beforeEach(function(){ var component = TestUtils.renderIntoDocument( <JsonTab ...

Verify the availability of a username before creating a new user account on an Android device

As I embark on creating my very first android application, the goal is to collect user data from a signup form and transmit it to a PHP backend. The PHP backend will then store this data in a database and provide a JSON encoded response indicating whether ...

Converting JSON array to a String and back to JSON in an Android application

Recently, I've been working on sending post data to my local PHP server. To make it easier to process the data later in PHP, I decided to format the post data as JSON. Using "Namevaluepairs", I converted my JSON array to a string and ended up with the ...

What's the best way to align this?

I have been working on a project and I want to make sure it's aligned properly for the user to view. Unfortunately, my current code doesn't seem to be doing the trick. Here's what I've tried so far: Below is an image of what I'm c ...

Unable to perform navigation during page load in a React.js application

I attempted to navigate to a route that should redirect the user back to the homepage when postOperations isn't set in the localStorage. To save time, please review the code snippet focusing on the useEffect and the first component inside return(). im ...

Exploring the Mechanism Behind the Successful String Interpolation of a Variable Imported in my Angular 2 Application

After making some modifications to my Angular 2 application, I encountered a situation where something started functioning properly sooner than I expected. This has left me puzzled about why it's working in its current state. Specifically, I have an a ...

How do I retrieve the enclosure URL in the Alexa Skill FeedHelper.js file?

I am currently working on a project to create an Alexa feed skill using a blueprint provided by Amazon. The blueprint involves calling RSS feeds from a URL, transforming them into JSON format, and saving them on Amazon S3. The code responsible for this fu ...

Issue with handling large numerical values during Json serialization in C# ASP.NET WebApi (2/Core 3.1)

Encountering an issue with large numbers (Int64/UInt64) being rounded during ASP.NET Json serialization has been a problem for me. This issue persists in both ASP.NET WebApi2 (.NET 4.5.2) and ASP.NET Core WebApi (Core 3.1). Here is my DTO class: public c ...

Sending data between Angular and Python using both strings and JSON formats

Seeking assistance with a Python script that sends events to a server. Here is the code snippet: LOGGER = logging.getLogger("send_event") POST_EVENT_URL = "http://localhost:3000/event/" def send(name, data): url = POST_EVENT_URL + name headers = {& ...

Issue encountered with Typescript when attempting to generate a recursive type object

My challenge is to create a recursive style object that can handle style properties in a nested format. Despite trying various solutions from SO and Google, I'm still struggling to understand how to do this effectively. interface Properties { border ...