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

"Interactive jQuery feature allows users to edit table content live with the ability to update and delete data via

I am working on implementing live editing, updating, and deleting functionality in a table using jQuery. However, I have encountered two problems: When clicking the pen icon from order #3 to #1, it requires 3 clicks, but when clicking from order #1 to ...

Using Special Characters in React JS Applications

When handling CSV uploads with accented characters such as émily or ástha, I encountered the need to encode and pass them to the backend. Experimenting with different approaches, I tried adjusting the file type in FormData from 'text/plain' to ...

Dealing with cross-origin error issues when using json.parse in React / MERN development

My data structure functions correctly when I use console.log: console.log(JSON.parse([values.category2]).needed_skills); However, when I pass the output of JSON.parse([values.category2]).needed_skills to a component in my application, the entire system c ...

The event listener for browser.menus.onClicked is dysfunctional in Firefox

Currently, I am in the process of developing my own Firefox extension and I have encountered an issue with adding a listener to an onclick event for a context menu item. manifest.json { "manifest_version": 2, "name": "My exten ...

Switch to a different element by rolling over one

I need assistance with a menu setup where the submenus are located in separate divs on the page. Both the parent elements and submenus have numerical identifying IDs, and I am struggling to create a rollover effect that would automatically open the corresp ...

Extracting information from an ENORMOUS Array

Let's start with my code snippet, featuring an array: var UserProfiles = [{ userProfileID: 1, firstName: 'Austin', lastName: 'Hunter', email: 'test', token: '', platform: 'android ...

Verify whether the initial value is distinct from the subsequent one using AJAX

I'm currently working on a project where I need to compare the first value received from an AJAX call to the subsequent values. However, I seem to be stuck and unable to figure out how to achieve this. Every 5 seconds, I am checking the follower count ...

`"Type is invalid" error occurring with component after importing it into a different project``

I am currently working on developing a custom Storybook 7 Typescript component library with React. I have successfully imported this library into another project using a private NPM package. However, one of the components in the library, specifically the ...

Send data from input to controller without using $scope

I am encountering an issue with the code below. Typically, I would resolve this problem using $scope, but this time I have been asked to find a solution without utilizing $scope in the controller. I am implementing the "controller as" syntax for managing ...

Strip the CSS styling from an image (the CSS being included in the generated code)

I need to remove the CSS styling from an image, but I can't modify the generated code where it's coming from. My actual code looks like this: <div class="bubble"> <img id="one" src="/static/webupload/MyronArtifacts/images/descarga.png ...

What is the best way to retrieve data from the next page in a Protractor test?

I am currently in the process of automating the test for booking a flight. When I enter the credentials on the homepage, click the Submit button, and the browser navigates to the search results page. const EC = protractor.ExpectedConditions; describe( ...

Content formatted with a gap

I wish to include a gap between each sample usage with markdown. For instance: .kick Sarah, .kick John, .kick Mary .setDescription(`**Usage :** \`${settings.prefix}${command.help.name} ${command.help.usage}\`\n**Example :** \`${setting ...

What do you believe to be superior: Vue UI design?

Scenario: Application managing multiple user roles. A view with extensive conditional rendering in the template. a) Is it preferable to have numerous conditional statements in a single view's template? b) Should separate views be created for each ro ...

Switch image on click (toggle between pause and play buttons)

Having some difficulty setting up a 3D audio player in A-Frame where the pause and play button images need to change depending on whether the audio is playing or not. Interested in seeing my code in action? Check it out here. ...

How to implement the Ionic ToastController without being confined to a Vue instance

I am currently facing a challenge while trying to utilize the ToastController of Ionic outside a vue instance. I have created a separate actions file which will be loaded within the vue instance, handling a request. Within this request, certain validations ...

Adding or removing a class using Jquery based on the condition of form validation

I am facing a problem with the following code that adds and removes classes to bring the next stage of the form. The form progresses step by step where certain fields need to be filled before validation on the next button, followed by filling other fields. ...

Looking to transform this PHP function into a jQuery function that generates all the possible combinations of values in an array?

I stumbled upon this PHP code on a programming forum. Here's the original code snippet: function everyCombination($array) { $arrayCount = count($array); $maxCombinations = pow($arrayCount, $arrayCount); $returnArray = array(); $conve ...

Leveraging the power of jquery-tmpl with the responseText

I am currently working on populating jquery-templates retrieved through an ajax call from a different folder on the server. I attempted to fill the responseTexts using .tmpl({..}) but unfortunately, it didn't work as expected. Here is my approach: va ...

Linux web server blocking requests across different domains, even with correct Access-Control-Allow-Origin headers set

I am facing an issue with my Ubuntu web server running a React app. There are two files on the server that handle requests made by the website, but for some reason, clients are unable to make requests to the server. Server.js: const express = require(&apos ...

Can you explain the distinction between browser.sleep() and browser.wait() functions?

Encountering timing problems with my protractor tests. Occasionally, test cases fail because of network or performance-related issues. I managed to resolve these issues using browser.sleep(), but recently discovered browser.wait(). What sets them apart an ...