Activate a module within a Vuex action only upon dispatching

Is there a way to import a package for use in a Vuex Action only when the Action is dispatched, in order to reduce the size of my entry bundle?

Here's what I've tried:

export const actions = {
  async createNewBin(store, bin) {
    const firebase = require('firebase/app');
    require('firebase/firestore');

    const collectionRef = firebase.firestore().collection('bins');

    try {
      const docRef = await collectionRef.add(bin);
      return docRef;
    } catch (e) {
      return e;
    }
  }
}

The firebase/firestore package is currently included in my entry file, but I want to avoid that.

Answer №1

Here is a solution that should be effective: https://webpack.js.org/guides/code-splitting/#dynamic-imports

const actions = {
    async createNewBin(store, bin) {
        const { default: firebase } = await import(
            /* webpackChunkName: "firebase" */ 'firebase')

        // Ensure that firebase is only initialized once.
        if (!firebase.apps.length) {
            firebase.initializeApp({
                // your init options
            });
        }

        const collectionRef = firebase.firestore().collection('bins');

        try {
            const docRef = await collectionRef.add(bin);
            return docRef;
        } catch (error) {
            return error;
        }
    },
}

Answer №2

For more information regarding this method, feel free to explore the following link:

Exploring webpack for lazy loading: When and when not to use

In simpler terms, you can consider implementing a solution similar to Eric's suggestion using async/await.

const { default: myModule } = await import(/* webpackChunkName: "myModule" */ 'myModule')

Alternatively, you can opt for a Promise-based approach like demonstrated below:

if(needToLoadMyBundle){
    import('myModule').then( myModule =>{
        // perform actions with myModule.default
    });
}

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

Make sure to remain in the same division area when refreshing the page

Whenever I click the next button and move to step 2, I want the page to stay on the same div even after reloading. The two divs used are join_form_1 and join_form_2 Currently, when I reload the page, it reverts back to the first div. Is there a way to e ...

How can I make sure to consider the scrollbar when using viewport width units?

I've been working on developing a carousel similar to Netflix, but I'm facing an issue with responsiveness. I've been using a codepen example as a reference: Check out the example here The problem lies in the hardcoded width and height use ...

What are the advantages of compiling our CSS and JS files in Laravel? How does it benefit us?

Just starting out with Vue and came across a video where they were compiling their assets. Got me thinking, why do we need to compile our assets? Can we use Vue and Vue-router in Laravel without asset compilation? If so, how? ...

Setting up jsonReader for jqGrid Configuration

I am having trouble displaying data in my Jqgrid. The Json data is coming from a web server, so I am attempting to format it using Jsonreader as a function. Could someone please help me identify any mistakes? Thank you in advance. Here is the code for the ...

Axios is returning a 401 (Unauthorized) error when attempting to retrieve user data from a React frontend and pass it to DRF Social Oauth2. Strangely, the same process

Here are the contents of two files, LoginScreen.JS and login.JS. The LoginScreen.JS file contains a submit handler that submits user input, while we import the axios instance from login.JS. In addition, a working example from PostMan has been provided. lo ...

Retrieve all the Firebase keys within a Vue script using Vue-Firebase

Trying to understand Firebase's handling of entries, I've been attempting to retrieve all keys from a child node. <div v-for="item in TeamArray"> {{item['.key']}} </div> Retrieving the keys from the HTML section works ...

"Bringing the power of JavaScript to your WordPress

I have set up a wordpress page and integrated some JavaScript into it. When working in wordpress, there are two tabs on a page where you can input text - 'Visual' and 'Text'. The 'Text' tab is used for adding HTML and scripts ...

Generating a dropdown menu in HTML using JSON entities

I am attempting to populate an HTML Select element with data retrieved from JSON. Below is a simplified version of the JSON object: {"Group1": "TestGroup1", "Group2" : "TestGroup2", "TotGroups" : "2"} To achieve this, I am using JQuery and AJAX for fetch ...

Guide to implementing if else statements with Protractor

I am facing some unusual situations and I'm not quite sure how to address them. As a newcomer to testing, I've been tasked with testing a website's cart function for proper functionality. The challenge arises when we add a certain number o ...

Manipulate a value using JavaScript

While the intention is for the button value to switch between 1 and 0, the echo $_POST["ordina"] consistently returns 1. Despite checking the code multiple times, I am unable to identify the issue. <script> function order() { if (document.ordination ...

Is it possible to modify @page directive(CSS) values from the code-behind(C#) or JavaScript?

Using the @page directive, you can define the printer margins for a page separately from regular CSS margins: <style type="text/css" media="print"> @page { size: auto; /* auto is the current printer page size */ margin ...

Struggling with populating a dropdown in MVC with JSON data fetched from an API using jQuery/JavaScript

I am struggling to bind the JSON data retrieved from an API to a dropdown list. I am having trouble extracting the values for id and name from the JSON format shown below: { "categories": [ { "categories": { "id": 1, ...

Determining User Login Status in Laravel using jQuery

While I am familiar with the authentication verification in laravel, I am interested in learning how to verify it using jQuery. Specifically, I want to make changes to my CSS when a user is logged in. By default: body{ background: url('image.jpg ...

Running javascript code after the completion of the render method in Reactjs

I am working with a ReactJS component: const com1 = React.createClass({ render: function() { return ( <a href='#'>This is a text</a> ); } }); I am looking to run some Javascript/jQuery code once the rendering ...

Tips for positioning a div relative to another div while controlling its z-index

Hey there, take a look at the image below https://i.sstatic.net/zYiaY.png The issue I'm facing is quite common - I have div 1 and div 2 visible in a loop, but divs 3 are hidden. When div 2 is clicked on, everything is great so far. However, what I wa ...

The getMonthlyBalances function is providing inaccurate results when calculating stock balances

One of my functions is called getMonthlyBalances, which takes in two arrays - stocks and trades. It calculates the monthly balance of a user's stock holdings based on their trade history. The stocks array includes objects with stock ID, prices, and da ...

Determining if a URL links to an image when the file extension is not informative

I am currently working on building an AJAX call to retrieve data from an API with a messy data structure. The challenge I'm facing is that the array returned by each AJAX call can contain up to 30 elements, some of which have image URLs without a file ...

The presence of a default value within an Angular ControlValueAccessor triggers the dirty state due to

My task is to create dynamic Input components for a template driven form using a directive. The default value of the Input component should be set by the component itself. However, I encountered an issue where setting a default value automatically marks t ...

I'm looking to learn how to implement the delete method in an API using TypeScript. Can anyone help me out

I am seeking guidance on utilizing 'axios' within 'nuxt.js'. I have experimented with sample data, and I am particularly interested in learning how to utilize the 'axios' method within 'nuxt.js' using TypeScript. T ...

Mastering the Rejection of Promises in Javascript with Graceful Elegance

One effective pattern using ES2017 async/await involves: async function () { try { var result = await some_promised_value() } catch (err) { console.log(`This block will be processed in a reject() callback with promise patterns, which is far mo ...