Leveraging external variables in a webpack bundle

I am working on a single page app using Vue and Webpack. Typically, Webpack generates a bundle with various chunks such as app.js and vendor.js. Currently, I am in the process of putting this static spa distribution into a Docker container. My main question is whether there is a way to inject additional JavaScript after the bundle has been created and packaged (in the dist directory) so that I can include specific variables for each deployment. This would be particularly useful for changing the API URL. What would be the most effective approach to achieve this?

Answer №1

One approach is to store your appconfig.json file in the dist folder and then use axios to fetch it within your /src/main.js file. Here's an example:

// Add your imports here
// ...

if(process.env.NODE_ENV === 'production') {
    axios.get('./appconfig.json')
        .then(response => {
            const config = response.data;
            const host = axios.defaults.baseURL = config.baseURL;
            // Other production configurations

            new Vue({
                el: '#app',
                router,
                components: {App},
                template: '<App/>'
            });
        });
} else {
    // Development configurations

    new Vue({
        el: '#app',
        router,
        components: {App},
        template: '<App/>'
    });
}

By modifying properties in the appconfig.json file, you can update settings in the app without requiring a rebuild or server restart when the user refreshes the page.

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

Nestjs gracefully shutting down upon starting the container

Whenever I try to run my container, it exits immediately. I am currently using Nestjs and Postgres in my setup. Below is the Dockerfile that I'm working with: FROM node:14.5.0 AS build WORKDIR /src RUN apt update && apt install python -y ...

Embed a subcomponent within another component triggered by an onClick event in ReactJS

Watch this quick demo to see my project in action. So, here's the deal - I have a menu with different options, and when "Tickers" is selected, I want it to display the Tabs component. However, if any other menu option is chosen, I don't want the ...

The bundle injected by Webpack-dev-server into the HTML page fails to display any rendered content

Whenever I execute webpack-dev-server (Command: "webpack-dev-server --mode development --open --progress --hot"), the bundle gets injected into the html page, but nothing actually appears on the screen. This is how my Webpack.config.js file looks like: v ...

Issue with data sorting in Laravel backend not reflecting properly in Vue frontend

Issue at hand: When fetching and displaying rows from a database using Laravel controller and Vue, the sorting order seems to be affected. Even though Laravel properly sorts the results from the model by name, once fetched through Vue and displayed in an ...

How can dynamically added data be retained in a table after reloading the page?

I have a piece of JavaScript code that is functioning properly, but the dynamically inserted data in the table gets lost after reloading the page. I am also implementing server-side validation and need to ensure that the dynamically added data persists e ...

ng serve issue persists even after resolving vulnerabilities

Can anyone assist me in resolving why I am unable to start my project after fixing 3 high vulnerabilities? I ran npm audit to identify the vulnerabilities and then used npm install --save-dev @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Display all active services in a new list item using AngularJS Ionic's ng-repeat directive

I've been working on a shopping cart feature for my Ionic app and everything is coming together nicely, except for the running itemized total. By default, the items in my array are set to active:false and when selected, they switch to active:true and ...

Having trouble with the "initSdk" property being undefined in your React Native Appsflyer integration?

I'm currently facing an issue while trying to integrate AppsFlyer into a react native application. The error I am encountering is "Cannot read property 'initSdk' of undefined" Initially, I imported the react-native-appsflyer module as shown ...

Utilizing API data to populate dropdowns within a React form and integrating selected values

I'm currently working on developing a reusable dropdown component for use in a React edit form scenario. The process involves selecting a record from a table to edit, which then opens a modal containing the edit form. The edit form's current valu ...

Navigating an array index within a v-for loop in Vue.js

I am facing an issue with assigning colors to elements in my component using data from Vuex state. I have an array of colors in my Vuex state and I want to specify a color for each element that comes from v-for loop. // state state: { APIData: { ...

Eliminate Tracking Parameters from URL

I rely on UTM parameters to monitor incoming links within Google Analytics. Consider a scenario where my URL appears as follows https://www.example.com/store?utm_source=newsletter&utm_medium=email&utm_campaign=spring_sale I am looking to streaml ...

Assistance with Ajax for content loading

Greetings, I am encountering an issue with the following code snippet (located in a js file named ajax.js) $(function(){ $("#loading").hide(); $("ul#nav a").click(function(){ page = "content/"+$(this).attr('href') ...

Combine various choices into a select dropdown

I am facing an issue with an ajax call in codeigniter where the response always consists of two values: team_id1 and team_id2. Instead of displaying them as separate values like value="1" and value="2", I want to join them together as value="1:2". I have ...

What causes getServersideprops to return undefined?

The data I am trying to fetch is showing as undefined in the console. Here is the code snippet: export default function Home({ data }) { console.log(data); return ( <div> <h2>Welcome !!</h2> </div> ); } export a ...

Consistently encountering the message 'Error: timeout of 2000ms exceeded' while using Selenium

Good morning, Currently, I am in the process of learning how to use Selenium with JavaScript (specifically using Mocha). I have created a very basic test that is causing some issues during runtime. Whenever I run the test, a new instance of Chrome opens a ...

What is the best way to integrate an array from an external JavaScript file into a Vue.js component?

I am struggling to import an array into a Vue component: This is my simplified component: <script type="text/babel"> const codes = require('./codes.js'); export default { props: [], data() { return { ...

Is the screen size detection malfunctioning when using Vue 3's computed property?

How do I accurately detect screen size in Nuxt 3? I have tried using the code below, but the screen size always shows as 1200. It seems that the computed property is being executed before the onMounted() hook. How can I resolve this issue? <template> ...

Difficulty encountered when attempting to utilize keyup functionality on input-groups that are added dynamically

I've exhausted all available questions on this topic and attempted every solution, but my keyup function remains unresponsive. $(document).ready(function() { $(document).on('keyup', '.pollOption', function() { var empty = ...

Creating function names and parameters dynamically during a call

I'm attempting to simplify a potentially lengthy switch case into a more concise expression in nodejs. Here's what I currently have: exports.ManagerRequest = functions.https.onCall(async (data, context) => { console.log(&apos ...

The computed function in Vue.js fails to provide a return value

I'm currently experimenting with a basic to-do list using vue.js. My goal is to calculate the total sum of all price values within an array. I created a small function under computed, but it seems like something isn't working correctly. Here&apos ...