Import a fixed JSON document in Webpack

In the code I have, there is a construction that looks like this:

var getMenu = function () {
    return window.fetch("portal/content/json/menu.json").then(function (data) {
        return data.json();
    });
};

I attempted the following in my webpack.config.js:

module: {
    loaders: [
        ...
        {
            test: /\.json$/,
            exclude: /node_modules/,
            use: [
                'file-loader?name=[name].[ext]&outputPath=portal/content/json'
            ]
        },
        ...
   ]
}

How the project is structured:

dist
  content
     json
        menu.json <- not found here

src
  content
     json
       menu.json <- original file

The Question:

Is there a way for webpack to move src/content/json/menu.json to dist/content/json/menu.json ?

Answer №1

When making a request for a JSON file using fetch, the retrieval only takes place at runtime. It's important to note that webpack will only process items that are explicitly imported. This means that if webpack started handling arguments passed to functions, it would confuse those arguments as modules and disrupt the functionality of the function.

To trigger your loaders, you can simply import the file into your project:

import './portal/content/json/menu.json';

An alternative approach is to directly import the JSON data instead of fetching it at runtime. With Webpack 2, the default loader for .json files is json-loader. By removing the .json rule, you can import the JSON like this:

import menu from './portal/content/json/menu.json';

The variable menu now contains the same JavaScript object that your getMenu function would return.

Answer №2

If you want your JSON to be loaded at runtime or deferred, you can utilize the fantastic dynamic imports feature in webpack:

import(
    /* webpackChunkName: "json_menu" */
    './portal/content/json/menu.json'
);

This will result in a Promise that resolves to the module object, with the "default" field containing your data. Here's an example using ES6 syntax:

import(
    /* webpackChunkName: "json_menu" */
    './portal/content/json/menu.json'
).then(({default: jsonMenu}) => {
    // Manipulate the "jsonMenu" variable as needed
    console.log('My menu:', jsonMenu);
});

Keep in mind that dynamic imports require the Babel plugin syntax-dynamic-import, which can be installed via npm:

npm install babel-plugin-syntax-dynamic-import --save-dev

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

Encountering a problem when extracting a nested object value from JSON using GSON

How can I print the address element to console for the given JSON? This Java Class contains all the data types of JSON keys and 3 classes: CustomerDataType, PhoneNumber, and Address. [ { "firstName": "Lakshay", "lastName": ...

Combining numerous objects into one object within an array, each with distinct keys, and displaying them using FlatList

I'm struggling to present this information in a FlatList. Array [ Object { "-N1gqvHXUi2LLGdtIumv": Object { "Message": "Aeaaeaea", "Message_CreatedAt": 1652167522975, "Message_by_Ema ...

I provided Array.Filter with a function instead of a predicate, and surprisingly it gave back the entire array. How is that possible?

I encountered an unusual scenario where I passed a function instead of a predicate to Array.filter. This function modified individual student objects and the filter returned the whole array. This led me to question, why is this happening? According to co ...

Is there a way I can appropriately display an image in a specific size box?

Check out the code snippet I wrote below: import React from 'react' function OurCourse() { return ( <div className='w-full '> <div className='w-full h-[390px]' style={{ backgroundImage:&apos ...

Utilizing Nuxt3's auto-import feature alongside Eslint

I'm having trouble finding an eslint setup that is compatible with Nuxt3's auto-import feature to prevent no-undef errors. I have tried various packages like @antfu/eslint-config, plugin:nuxt/recommended, @nuxt/eslint-config, @nuxtjs/eslint-confi ...

Angular dropdown menu with 2 options

Looking to implement a select box with various price ranges to choose from. For example: - 0 to $2,000 - $2,000 to $3,500 - $3,500 to $5,000 - $5,000 to $7,500 - $7,500 to $10,000 - $10,000 Once a user selects an option, I want to automatically set the ...

Is there a way to incorporate a CSS file into this without explicitly mentioning the color?

I have successfully implemented a PHP solution for changing themes with a cookie that remembers the selected theme color when the user leaves the site. However, I now need to switch this functionality to JavaScript while still utilizing the CSS file. How c ...

Retrieving text from a JSON variable located between two specific strings, especially if the second string appears multiple times

I have a wall of text generated from a JSON dataset and need to extract a specific string hiding within it. The text block is saved as the variable @name. "re_id":110482,"username":"John Smith", My goal is to isolate "John Smith" from this complex strin ...

Populate HTML dropdown menu with data from an external JSON file

I'm attempting to populate a HTML Dropdown menu with information from an external JSON file, which consists of the following { "Destinations": [ { "destinationName": "London", "destinationID": "lon" }, { "dest ...

Show alerts that automatically disappear after a set amount of time

I have successfully implemented code that displays alerts for a specific period of time, indicated by (alert alert-warning). Additionally, I want to display another type of alert, (alert alert-success), for a certain amount of time, after which the page sh ...

How can I implement code splitting in a React single page application?

I've developed a large application using reactjs and redux. My main concern is how can I minimize the page size? I am aware of code splitting in webpack, but my impression is that it's mainly for multi-page applications. In my case, I only have ...

Steps for ordering by a JSON attribute:

Within my JSON file, I have the following simple structure: {"Item1": {"p1": {"p1sub1": 8, "p1sub2": 7}, "p2": {"p2sub1": 6, "p2sub2": 5} }, "Item2": {"p1": {"p1sub1": 4, "p1sub2": 3}, "p2": {"p2sub1": 2, "p2sub2": 1} } } To retrieve this data, I use th ...

Deciphering the method to retain added text

Imagine you have this code snippet: $('.button').click(function() { $('body').append("<p>Random Text</p>"); }); Whenever the .button is clicked, text is added to the body. How can we make sure that this text is saved a ...

Can anyone please guide me on how to extract the IP address of a specific individual using Node.js?

There's an individual running some kind of exploit scanner on my server. I'm receiving strange requests like: IP ADDRESS: ::ffff:127.0.0.1 www-0 (out): POST /cgi-bin/php5?%2D%64+%61%6C%6C%6F%77%5F%75%72%6C%5F%69%6E%63%6C%75%64%65%3D%6F%6E+%2D%64 ...

The for loop does not pause for asynchronous code to complete

The for loop in my code has a function call that contains async code. However, the issue is that the for loop does not wait for the async code to return before continuing with the iterations. The function aFunctionThatRunsAsync is from a library that I ca ...

Utilizing jQuery AJAX to Send an HTML Array to PHP

In my current HTML forms and jQuery AJAX workflow within the Codeigniter Framework, I've encountered a common issue that has yet to be resolved to suit my specific requirements. Here's the situation: HTML - The form includes an array named addre ...

Creating dynamic templates in AngularJS using ng-include and custom template directivesHow to implement dynamic

I would like to develop a div that can load various templates dynamically, depending on a context parameter: Introducing my "search-results-container" directive: app.directive("searchResultsContainer", function() { restrict: "E", templateUrl: "search ...

Updating object values within a while loop using JavaScript

I am facing an issue with managing an array of JavaScript objects that have a property 'table' with values table1, table2, table3, or table4. Each table should only accommodate 6 members. I have implemented a while loop to check if 'table1&a ...

Wait for NodeJS to finish executing the mySQL query

I am attempting to send an object from the controller to the view. To keep my queries separate from the controller, I am loading a JS object (model). My model structure is as follows: function MyDatabase(req) { this._request = req; this._connection = ...

What is the reason for including parentheses when evaluating JSON data?

What is the purpose of adding ( and ) around the code when using eval? var strJson = eval("(" + $("#status").val().replace(";","") + ")"); Note: The result of $("#status").val() is similar to {"10000048":"1","25000175":"2","25000268":"3"}; ...