Webpack: Moving JSON files with the file-loader

Currently utilizing Webpack's module.loaders and file-loader to duplicate multiple js-files during compilation:

module.loaders = [
    { test: /app\/locale\/moment\/.*\.js$/, loader: "file-loader?name=locale/moment/[name].[ext]" }
];

Successfully achieving the desired result with js-files.
Now aiming to replicate the same process with JSON files:

module.loaders = [
    { test: /app\/locale\/.*\.json$/, loader: "file-loader?name=locale/[name].[ext]" }
];

Encountering issues this time around.
Curious as to why Webpack treats js and json files differently when utilizing the file-loader?

Answer №1

This is a modified version of my response to a similar question I had.

To easily move JSON files using file-loader, you can include the following snippet in your Webpack setup:

module: {                                                                    
    rules: [  
    // ...  
    {                                                                        
       test: /\.json$/,                                                       
       loader: 'file-loader?name=[name].json'                                 
    }
    // ...
    ]
}

There are a couple of things to note here: 1) file-loader will only duplicate files that are imported or required in your code, and 2) file-loader provides a path to where the file was loaded, not the actual content of the file.

To replicate a JSON file, you must first import it, like so:

const dataFile = require('../data.json');

As file-loader gives a path to where the file was loaded, dataFile will have the value "/data.json".

You can then access the contents of the JSON file using methods like jsonfile:

jsonfile.readFile(dataFile, function(err, obj) {
    console.log(obj);
});

or utilizing Angular's HTTP package:

http.get(dataFile).map(res => res.json()).catch((error: any): any => {
    // ...
}).subscribe(obj => {
    console.log(obj);
});

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

Import and load numerous JSON files into a responsive and visually appealing Bootstrap table

I am new to coding in javascript and I'm seeking assistance in loading multiple JSON files to populate a bootstrap table. Currently, I've managed to create a table by manually combining the content from different files into one variable called l ...

update the element that acts as the divider in a web address (Angular)

Is it possible to modify the separator character used when obtaining the URL parameters with route.queryParams.subscribe? Currently, Object.keys(params) separates the parameters using "&" as the separator. Is there a way to change this to use a differe ...

Is it possible to obtain the parameters using an empty object with the getStaticPaths function?

Within the getStaticPaths function, a path is returned with params postId:1. If additional params like postId: 2 or postId: 3 are included, they will also be statically generated. Is my understanding correct? Is there a way to avoid loading any post based ...

"Troubleshooting: Vue JS Axios Post Request Not Passing Data to PHP Server

After successfully uploading an image in Vue JS and sending a POST request to a Laravel Route, the JSON response from the API is displayed on the client side as expected. However, there seems to be an issue with retrieving this response in PHP, as it retur ...

Obtain the value or values of radio buttons based on certain conditions

Recently, I have been delving into .JS and grappling with pre-existing code. One of the challenges I face involves extracting data from radio buttons after a particular selection is made. The gist of it is related to transportation requirements. Upon indi ...

Utilizing a variable within an Angular filter: A step-by-step guide

Currently, I am in the process of experimenting with Angular. I am able to retrieve some data from the controller and successfully apply a filter when passing it as a string. However, I encounter issues when attempting to use a variable for the filter inst ...

Storing an array of objects in Firestore using JavaScript presents a challenge

I am attempting to save an object to Firestore which includes an array: { returnMode: false, id: "SE-74c5219a-acfe-4185-9e33-f78b10ac3f1e", prices: [ { price: { twoHours: 0, firstHour: 0, id: "zero&quo ...

Access to this page via the Odesk API in node.js is restricted and unauthorized

/** * Here is an example of how to use the oDeskAPI * * @package oDeskAPI * @since 09/22/2014 * @copyright Copyright 2014(c) oDesk.com * @author Maksym Novozhylov <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...

Connecting text boxes with JavaScript and JSON for gaming experience

I am currently developing a game and have encountered a slight issue. Currently, there is a text box in the game that prompts the player to run into it to progress to the next level. When the player does so, the next level loads seamlessly, which works per ...

Having trouble with JQuery's append method on the <head> tag?

I am having an issue with this particular code block. It seems to be unable to insert the meta tag into the head section. Any suggestions on how to resolve this problem? <html> <head> <title>hello world</title> </head> < ...

"Retrieve real-time information from the server directly on the client side

Within my express router, I validate the data submitted on a form and then render another page if the data is valid, passing along the form data. My goal is to be able to access this passed data on the client-side. In the chat.ejs view, I have a chatroom.j ...

Send information using jQuery AJAX

Currently, I am attempting to use AJAX to submit data to my table. Below is the form I have created for this purpose: <form> Total <input type="text" id="total" name="total" /><br /> Bill name<input type="text" id="bill-name" ...

Tips for utilizing the onload attribute alongside the ng-controller directive to run a function that has been established within the controller

When trying to call the submit() function as soon as the page loads, I keep encountering a submit() method not found error. The positioning of ng-controller and onload is confusing to me. If there is an alternate method in Angular to achieve this, please ...

Changing the format of JSON output in Laravel

Help me clean up my JSON output by removing unnecessary elements. This is my current Output: [ { "current_page": 1, "data": [ { "_id": "6580f69587f0f77a14091c22", ...

Issue encountered while attempting to compress tailwindcss

I attempted to reduce the size of my tailwindCSS by creating a script in my package.json: "tw:prod":"NODE_ENV=production npx tailwindcss-cli@latest build ./src/css/tailwind.css -o ./public/css/tailwind.css", However, I encountered the ...

{ 'Name:UniqueRewrite': { token: 738561, number: 2021.8 } }

Is there a way to extract the token value from this data in Node.js? console.log({'Name:Test': { token: 738561, number: 2021.8 } }) I need to isolate just the token and store it in another variable. ...

Looking to update a specific element in an array on an hourly basis?

var temperature = [-18 , -18.1 , -18.2, -18.3, -18.4, -18.5, -18.6, -18.7,-18.8, -18.9, -19 , -19.1 , -19.2, -19.3, -19.4, -19.5, -19.6, -19.7,-19.8, -19.9, -20]; $(".warlotemp").html(temperature[0]); $(".warlotemp").append(" C"); I am intere ...

Utilize JavaScript to extract data from an XML file through a specified

Hello, I am new to JavaScript, Currently, I am working on a project where I need to parse an XML File using JS and jQuery. Could you please advise on how to open an XML file based on its URL? var xml = "File.xml", xmlDoc = $.parseXML( xml ), $xml = $( x ...

Executing the onSuccess callback in Ajax without any ability to manipulate the ajax requests

My dilemma lies in needing to execute a JavaScript function upon the successful completion of an AJAX call. Unfortunately, I am unable to directly manage the AJAX calls as they are handled by the DNN5 framework. Is there a way for me to trigger my functio ...

Inspect all checkboxes created by JavaScript

I'm attempting to develop a checkall checkbox that will automatically select all the checkboxes I've created using JavaScript. Firstly, I gather the number of rows and columns from the user and then use JavaScript to generate a table and insert ...