What is the best way to separate my Webpack/Vue code into a vendor.js file and exclude it from app.js?

My plan is to create two separate files, vendor.js and app.js, for my project. In this setup, vendor.js will contain the core code for Webpack and Vue.js, while app.js will solely focus on the Vue.js code specific to my application. To streamline this process, I am utilizing the npm module laravel-mix to manage the asset bundling using Webpack.

The content of vendor.js is as follows:

window.Vue = require('vue');

On the other hand, app.js includes the following code snippet:

import App from './App.vue';

Vue.component('App', App);

new Vue({
    el: 'App'
});

The configuration in webpack.mix.js looks like this:

let mix = require('laravel-mix');

mix.js('src/js/vendor.js', 'public/js/')
   .js('src/js/app.js', 'public/js/')
   .sass('src/sass/vendor.scss', 'public/css/')
   .sass('src/sass/app.scss', 'public/css/');

Despite setting up the files accordingly, it seems that app.js continues to duplicate some of the core code present in vendor.js. As I load vendor.js before app.js, the redundant inclusion of Webpack core code in both files becomes unnecessary.

I am seeking guidance on how to structure vendor.js and app.js to achieve a clean separation of concerns. The current implementation in vendor.js feels somewhat messy since I'm resorting to the require function rather than the ES6 standard import, and attaching Vue to the window object for access in app.js.

An ideal scenario would involve the following structures:

vendor.js:

import Vue from 'vue';

app.js:

import Vue from 'vue';
import App from './App.vue';

Vue.component('App', App);

new Vue({
    el: 'App'
});

This approach appears cleaner and aligns better with modern ES6 practices, yet it compromises the purpose of vendor.js by duplicating the Vue import within app.js. My expectation was that Webpack would intelligently handle the duplication issue and only include the core code once. Why does it redundantly add the Webpack core code to both files?

Although I understand the technical rationale behind this behavior, I hope for a smarter implementation where the core code is imported only once. Is there a way to achieve this level of optimization?

Answer №1

Have you considered utilizing vendor extraction to optimize your code and generate a separate chunk for Webpack runtime? It can be quite beneficial. Check out more information at laravel.com/docs/5.7/mix#vendor-extraction.

P.S. If I'm understanding correctly, you are referring to the Webpack runtime code, correct?

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

AngularJS form submission with Ajax requiring a double click to successfully submit the form

I need to perform the following activities on my HTML page: User inputs email and password for registration Form is sent to Controller when user clicks Submit Controller uses AJAX to create JSON request to RESTful Server and receives response from server ...

Having trouble getting the Babel plugin transform-remove-console to function properly with the Vue CLI 4 and @vue/cli-plugin-babel/preset?

When you create a VueJS project using Vue CLI 4, Babel is configured with a useful preset in babel.config.js: module.exports = { presets: [ '@vue/cli-plugin-babel/preset', ], }; I am attempting to use babel-plugin-transform-remove-conso ...

Issue: Unable to find solutions for all parameters in NoteService: (?)

After following a tutorial on Angular 2 from , I encountered the mentioned error when running my API. The browser indicates that there are unresolved parameters in the following service: import {Injectable} from '@angular/core'; import { ApiSe ...

What is the best method for excluding past dates in the Ui calendar?

As a beginner with Ui calendar, I am seeking guidance on how to prevent users from selecting or interacting with previous dates in Ui-calendar using angularjs. While the Eventdrop, EventResize, and eventclick features are functioning properly for me, it ...

Best practice for structuring an object with multiple lengthy string elements in the GCP Datastore Node Library

My JavaScript object is structured like this: const data = { title: "short string", descriptions: [ "Really long string...", "Really long string..." ] } I need to exclude the long strings from the indexes, but I ...

The req.ip in Express appears to alternate between displaying my local machine address as ::ffff:127.0.0.1 and ::1 in an unpredictable manner

Simply put, the title sums it up. I've spent the last few hours working on a middleware function that uses cookies for authentication, like so: const authRoute = async (req, res, next) => { console.log(req.ip); // additional logic here ...

What is the best way to showcase content using Chakra-ui SideBar in a React Application?

After exporting the SideBar, I imported it into my App.jsx SideBar.jsx 'use client' import { IconButton, Avatar, Box, CloseButton, Flex, HStack, VStack, Icon, useColorModeValue, Text, Drawer, Draw ...

Avoid running multiple YouTube views simultaneously within an AngularJS application

Currently, I have an Angularjs application that displays a list of Youtube videos utilizing the videogular node module. An issue has arisen where users can play multiple Youtube videos simultaneously, leading to potential violations of Youtube's poli ...

What is the best way to determine the number of subchildren within a parent div using JavaScript or jQuery?

Can anyone assist me with counting the number of child divs inside a parent div using JavaScript or jQuery? I'm not very experienced in these languages. Below is my code snippet: $(function () { var parent = document.getElementById('parent& ...

One approach to animating elements on a web page is by utilizing Node.js

Imagine you want to programmatically define animated movement for elements on a web page. In JavaScript, this can be achieved using techniques outlined in this helpful guide: How TO - JavaScript HTML Animations. But how would you do this in Node.js? UPDAT ...

Steps to retrieve the primary key associated with a duplicate entry error (1062) in MySQL using the Knex.js library

Testing out the database by sending values from an HTML form has been successful so far. Unique inserts and good connections are working well. However, intentionally sending a duplicate username for testing purposes results in an error message - which is e ...

Setting the base path for a statically exported NextJS app

I am in the process of developing and deploying a React / NextJS application to a Weblogic J2EE server with a specific context. While I have some experience with React, I am relatively new to NextJS. The current steps for building and verifying the app ar ...

Error: JSON parsing failed due to an unexpected token "u" at the beginning of the JSON string. This occurred in an anonymous function when

Implementing reCaptcha in my firebase project has been successful. I am now sending form data and the captcha response using grecaptcha.getResponse() to my server upon clicking the send button. Below is the code snippet from client.js: $('.sendUrl ...

Unable to alter the height of the element

I am attempting to resize an element by dragging, similar to this example. I have created a simple directive for this purpose: @Directive({ selector: '[drag-resize]' }) export class DragResizeDirective { private dragging: boolean; const ...

The installation of vue-cli failed due to permission issues with error code EPERM in npm

I keep encountering an error message when I try to run npm install -g vue-cli: npm ERR! path C:\Users\End User\AppData\Roaming\npm\node_modules\vue-cli\node_modules\nan\package.json npm ERR! code EPERM ...

No parameters have been found in the $router.push function

Imagine this scenario: this.$root.$router.push({ path: '/dashboard', params: { errors: 'error' }, query: { test: 'test' } }) Within my component, I am using the above code to redirect to another URL when an err ...

A guide to swapping text in a jQuery DOM component

In order to construct HTML from a jQuery ajax response, I prefer not to nest unsightly strings in javascript and avoid using templating scripts like mustache. Instead, I decided to utilize a template HTML with display: none as shown below: <div id="mes ...

Exploring the power of AngularJS through nested directives

Index.html: <nav-wrapper title="Email Test"> <nav-elem value="first"></nav-elem> <nav-elem value="second"></nav-elem> </nav-wrapper> app.js: app.directive('navWrapper', function() { return { ...

Is there a different way to retrieve data in Node.js instead of using mysqli

<?php $connect = mysqli_connect('localhost', "root", "", "test"); if(!$connect){ die(mysqli_connect_error()); } $sql = "SELECT * FROM articles"; $result = mysqli_query($connect, $sql) or die ...

Node.js - Synchronize asynchronous calls to ensure coordinated execution in code

I am trying to figure out how to make a for loop with an async function wait until all the async functions called within it are finished before allowing the code to continue. In my scenario, I have a variable "bar" that contains a JSON array with other ne ...