简体   繁体   中英

How do I split my Webpack/Vue code into a separate vendor.js file and remove it from app.js?

I want to create vendor.js and app.js files for my project in which the vendor.js file contains the Webpack and Vue.js core code, and app.js only contains the Vue.js code written for my app. I'm using the laravel-mix npm module to wrap around Webpack and build all my assets.

vendor.js contains the following one line of code:

window.Vue = require('vue');

app.js contains the following code:

import App from './App.vue';

Vue.component('App', App);

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

And webpack.mix.js contains the following code:

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/');

When I do this, vendor.js is exactly what I want, just the Webpack and Vue.js core code, however, app.js also contains the Webpack core code. I'm loading vendor.js before app.js in my app, so I don't need the Webpack core code in both files.

How can I structure both the vendor.js and app.js files to get what I want? Also, the code I have in vendor.js seems a bit sloppy (ie, I'm using require instead of import and I'm attaching it to the window object so that the app.js file has access to the Vue object), and I'm wondering if there's a better way to do it. What I'd ideally like is something like the following:

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'
});

That seems "cleaner" to me and more inline with the ES6 way of doing things, but it kind of defeats the purpose of vendor.js , since app.js contains the same import for Vue.js. I thought Webpack was supposed to be "smart" enough to know that I have already imported Vue.js into the vendor.js file so that when I import it again into app.js , there's no need to bring all the Vue.js core code over again. Also, why does it add all the Webpack core code in both files?

Well, I kind of know the answer to that, but I'd like it to be smart enough to include the core code only once. Is that possible?

Using vendor extraction will help you with that + get you a separate chunk for Webpack runtime have you tried it? laravel.com/docs/5.7/mix#vendor-extraction

PS unless I misunderstood what you meant by Webpack code, you meant the runtime right?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM