Prevent Vue.js from bundling the settings file into the build

I have set up the vue-webpack template and created a settings.json file to hold environment variables that need to be changed during script installation.

Content of my settings.json file (containing the API server's absolute path):

{
  "apiURL": "//localhost/app/server/API"
}

How can I prevent the file from being minified or bundled in the production version, so that I can make changes to it and have the updated file used the next time the app is accessed without requiring a rebuild?

Within my app, I reference this file using require:

const SETTINGS = require('../settings.json');

I am aware that using require will cause webpack to bundle it as a module, but how can I incorporate it into my app in a way that allows the settings file to remain a separate file in the production build, which can be edited as needed?

Is there a more efficient format or method for storing these settings so they can be edited in production without necessitating a rebuild?

Answer №1

To specify those configurations, you can store them in an object that can be accessed through the externals parameter in webpack.config.js.

The externals parameter allows you to exclude dependencies from the output bundles. Instead, the generated bundle relies on the presence of that dependency in the consumer's environment.

For instance:

externals: {
  appSettings: "appSettings",
  "window.appSettings": "appSettings"
}

Here, appSettings is a global variable that holds the desired environment variables.


Alternatively, if you prefer to avoid exposing the settings in the global object, you can follow this approach:

Define a variable with the default settings, which will be bundled with webpack.

export var appSettings = {
  currentSettings: "",
  settings: {},
  getString: function(strName) {
    var sett = this.currentSettings ?
      this.settings[this.currentSettings] :
      appDefaultStrings;
    if (!sett || !sett[strName]) sett = appDefaultStrings;
    return sett[strName];
  },
  getSettings: function() {
    var res = [];
    res.push("");
    for (var key in this.settings) {
      res.push(key);
    }
    res.sort();
    return res;
  }
};

export var appDefaultStrings = {
  apiURL: "//localhost/app/server/API"
    //...
}
appSettings.settings["default"] = appDefaultStrings;

You can then import this variable and utilize it like so:

import appSettings from "../path/to/appSettings";

appSettings.getString("apiURL"); //"//localhost/app/server/API"

Once you have your default settings set, you can create another file for custom settings.

import appSettings from "../path/to/appSettings";

export var appProductionSettings = {
  apiUrl: "http://example.com"
    //...
}

appSettings.settings["production"] = appProductionSettings;

Lastly, determine which settings you want to use. If you're unfamiliar with vue.js, here's a guide to get you started:

import appSettings from "../path/to/appSettings";

export class MyApp {
  constructor() {
    this.settingsValue = "";
  }
  get settings() {
    return this.settingsValue;
  }
  set settings(value) {
    this.settingsValue = value;
    appSettings.currentSettings = value;
  }
}

Change the settings accordingly:

import "../path/to/productionSettings";

var app = new MyApp();

app.settings = "production";

This method allows you to create and utilize multiple settings files as needed.

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

Utilizing NextJS to fetch JSON data from the public directory

I am having trouble importing a globe.json file from my public folder. When I try to import it, I get the error message Module not found: Can't resolve '/globe.json' This is how my files are structured currently: public globe.json src ...

What is the best way to combine two JavaScript functions into a single function, especially when the selector and function to be invoked may differ?

In the provided snippet, I am using the following function callers: // del if ( maxDelivery > 0 ) { if ( maxDelivery === 1 ){ delAdressFunc( dels ); } else { for ( i = 0; i < maxDelivery; i += 1 ){ delAdressFunc( ...

What is the functionality of a nested child directive root element when placed at the same level as the parent directive root element?

Hello there, I'm currently facing a unique situation that has me stumped. Is it possible to replace the content of a directive's root element with that of a nested (child) directive? Here is an example scenario: <div id=”main”> <n ...

Display localization keys in Vue using i18n

Are there any ways to display the keys using localization? I came across a solution in the documentation which suggests creating decision maps for fallbackLocale. My approach was to define a decision for default -> en and a decision for 'not-a-lan ...

Prevent the left border from displaying on a link that wraps to a new line

Excuse me, I am facing an issue with a pipe separator in my subnav bar between links. The problem is that the first link on a new line retains the left-border that should be disabled. How can I prevent this border from appearing on the first link of a new ...

Addressing the Cross Domain Issue when Implementing DHIS 2 API with jQuery

Today, I spent hours trying to authenticate my javascript application with the DHIS 2 API using Jquery. According to the API documentation (https://www.dhis2.org/doc/snapshot/en/user/html/ch32s02.html), base 64 authentication is required. However, my attem ...

What is the process for logging in a user using an access token retrieved from an API in Vue.js?

I'm feeling a bit lost after obtaining an access token from Vue.js. I'm not sure how to use this token to log in a user. After setting up the login frontend, I successfully connected it to my Django backend using simplejwt. Although I've ma ...

Retrieve information from the var variable following the deserialization of JSON

I am encountering an issue while attempting to deserialize a JSON string into an object. Below is the method that I have employed: var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json1); var pc= dict["getresults"] ...

We were unable to find an existing Kibana index, therefore we are unable to establish a connection

When setting up vue-storefront-api and vue-storefront on my Windows machine, I encountered an error in windows Power Shell or Command Prompt while running docker-compose up. The error message stated that no existing Kibana index was found, along with the i ...

Can you identify the issue with this particular JSON parsing function's reviver?

I am trying to parse a JSON string with a reviver function to only include specific properties. Here is my code snippet: const whitelist = ['prop1', 'prop2', 'result']; const reviver = (key, value) => { if (whitelist.i ...

Chart.js encounters difficulties displaying the chart due to the data in reactjs

My goal is to utilize chartjs-2 to showcase a bar graph with data. Below is the code I've implemented: import React from "react"; import { Bar, Line, Pie } from "react-chartjs-2"; export default class App extends React.Component { constructor(pro ...

Loading images dynamically in ReactJS allows for a seamless and customized user experience

I've been trying to dynamically fetch images from my images folder based on data retrieved from the database. Despite searching through numerous resources, I'm still struggling to crack this issue. Check out my code snippet below: import sword fr ...

Setting up the InMemoryCache in Vue ApolloConfiguring the InMemoryCache

I've set up vue-apollo following the instructions in the apollo.config.js file from this guide: (I'm using VSCode). Now, I want to configure the InMemoryCache to exclude the typeName (addTypename: false) like it's explained here: https://w ...

Refreshing data causes the data to accumulate and duplicate using the .append function in Jquery

I am currently working with a dynamic table that is being populated using AJAX and jQuery. Everything seems to be functioning correctly, however, I am encountering an issue when trying to reload the data as it just continues to stack up. Below is the func ...

Icons in CKEditor are not showing up on iPad devices

Experiencing Toolbar Icon Issues on CKEditor I am encountering an issue with the toolbar icons not appearing on the CKEditor when using it on an iPad with Safari. CKEditor Version: 4.3.2 Investigation The CKEditor functions properly on all other browse ...

How to best handle dispatching two async thunk actions in Redux Toolkit when using TypeScript?

A recent challenge arose when attempting to utilize two different versions of an API. The approach involved checking for a 404 error with version v2, and if found, falling back to version v1. The plan was to create separate async thunk actions for each ver ...

Make a diagonal border using CSS styling

Is it possible to create a slanted border like the one shown in this image (red line) using CSS/CSS3 or JavaScript? <div id="DIV_1"> <img src="/uploads/2016/01/logo.jpg" width="250px" id="IMG_2" alt='' /> <nav id="NAV_3"& ...

Having trouble establishing a connection to the server through curl

Whenever I attempt to send a request to the server on localhost, I keep getting this error message: Error: call to URL failed with status 200, response {"resultCode":503,"resultMessage":"Yakeen Failure: The ID Is Not Found at NIC","referenceNum ...

The operation could not be completed with exit code 1: executing next build on Netlify platform

Having trouble deploying my Next.JS site to Netlify due to a build error. The site was working fine previously. Any suggestions on how to resolve this issue? 3:43:14 PM: - info Generating static pages (2/6) 3:43:14 PM: - info Generating static pages (4/6) ...

Exploring JSON using patterns with the power of MYSQL Regex

I am facing some challenges with a project... It's like an experiment or something along those lines... It involves a Relational database with Json elements, resembling a form response. For example: Select details from mytable where id = 1 and the ...