Vite offers a superior development experience for Vue 2 projects, although its default build output may require adjustments for direct file browsing or legacy browser compatibility. A hybrid approach leverages Vite for the development server speed while utilizing Vue CLI for the production build process. This ensures compatibility with older environments often required by Electron or legacy web platforms.
Environment Specifications
Node.js: 14.21.3
Electron: 12.2.3
Element UI: 2.15.14
Node.js: 14.21.3
Electron: 12.2.3
Element UI: 2.15.14
The
package.json file defines separate scripts to trigger the correct toolchain. The serve command runs Vite for hot-reloading, while build invokes Vue CLI to generate the production assets.{
"name": "vue2-electron-starter",
"version": "1.0.0",
"scripts": {
"serve": "vite --port 8080",
"build": "vue-cli-service build",
"preview": "vite preview --port 4173",
"lint": "eslint . --ext .vue,.js --fix"
},
"dependencies": {
"element-ui": "^2.15.14",
"pinia": "^2.0.16",
"vue": "^2.7.16",
"vue-router": "^3.5.4"
},
"devDependencies": {
"@vitejs/plugin-vue2": "^2.3.1",
"vite": "^4.4.1",
"@vue/cli-service": "~5.0.0",
"vue-template-compiler": "^2.7.16",
"terser": "^5.14.2",
"eslint": "^8.5.0",
"eslint-plugin-vue": "^9.0.0"
}
}
The
vite.config.js configures the development server and build output structure. Using a relative base path is crucial for Electron compatibility.import path from 'path';
import { defineConfig } from 'vite';
import vue2Plugin from '@vitejs/plugin-vue2';
export default defineConfig({
base: './',
plugins: [vue2Plugin()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
build: {
rollupOptions: {
output: {
chunkFileNames: 'assets/js/[name]-[hash].js',
entryFileNames: 'assets/js/[name]-[hash].js',
assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
},
},
},
});
For production builds,
vue.config.js handles the configuration. It allows setting up external CDN links for libraries like Vue and Element UI to reduce bundle size, and dynamically selects the HTML template based on the build environment.const { defineConfig } = require('@vue/cli-service');
module.exports = defineConfig({
publicPath: './',
configureWebpack: {
externals: process.env.NODE_ENV === 'production'
? {
vue: 'Vue',
'vue-router': 'VueRouter',
'element-ui': 'ELEMENT',
vuex: 'Vuex',
}
: {},
},
chainWebpack: (config) => {
config.plugin('html').tap((args) => {
const isProduction = process.env.NODE_ENV === 'production';
// Switch templates for different build targets
args[0].template = isProduction ? './public/index.prod.html' : './public/index.dev.html';
return args;
});
},
devServer: {
port: 8080,
},
});