background
Recently, I am working on the technology stack transfer of the company’s project. The technology stack based on the old project is VUE2, so the new technology stack adopts the mode of VUe3 + Vant. In addition, the new TS + ESLint configuration improves the maintainability of projects. The project packaging tool still uses WebPack in the formal environment, while there are two packaging modes in the development environment: Vite and WebPack. Vite is based on the browser ES Moudle and has the advantages of fast packaging and small size, which is conducive to rapid development of projects. However, since Vite itself is not recommended for the production environment and the production environment needs higher stability, so the development and production have jointly built a set of WebPack packaging method to facilitate the investigation of daily problems. This article only Outlines the development framework and packaging configuration for your reference.
The project structure
Basic configuration
After making clear the technology stack, first set up the environment configuration of VU3 + Webpack + TS + Babel. Since the old project uses Node to modify static page values, vue-CLI scaffolding is not considered. Initialize the yarn init page and install vue3+babel7+typescript dependencies. The following points should be paid attention to:
- The babel.config.js file requires additional plug-in processing for the Vant framework
plugins: [
[
'import',
{
libraryName: 'vant'.libraryDirectory: 'es'.style: true
},
'vant']]Copy the code
- Node_modules must be removed during TS configuration to avoid verification of dependencies and increase project compilation time
"exclude": ["node_modules"]
Copy the code
- Tsconfig. json also needs to be configured in addition to webpack files
// webpack.base.js
"alias": {
// direct to SRC with @
The '@': path.resolve(__dirname, '.. /src'),
'@libs': path.resolve(__dirname, '.. /src/libs'),
'@cp': path.resolve(__dirname, '.. /src/components'),
"@store": path.resolve(__dirname, '.. /src/store'),}//tsconfig.json
"paths": {
"@ / *": ["src/*"]."@libs/*": ["src/libs/*"]."@cp/*": ["src/components/*"]."@store/*": ["src/store/*"]."@store": ["src/store"]},Copy the code
Vite configuration
1. Installation of vite depends on YARN add vite @vitejs/plugin-vue vite-plugin-style-import
2. Install the less processing style and configure the vite compilation mode
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import styleImport from 'vite-plugin-style-import'
import path from 'path'
export default defineConfig({
plugins: [
vue(),
styleImport({
// Handle the introduction of the Vant framework
libs: [{libraryName: 'vant'.esModule: true.resolveStyle: name= > { return `vant/es/${name}/style`}}]})],// Path alias
resolve: {
alias: {
The '@': path.resolve(__dirname, './src'),
'@libs': path.resolve(__dirname, './src/libs'),
'@cp': path.resolve(__dirname, './src/components'),
'@store': path.resolve(__dirname, './src/store')}},css: {
preprocessorOptions: {
less: {
modifyVars: {
hack: `true; @import (reference) "${path.resolve( __dirname, './src/styles/global.less' )}"; `
},
javascriptEnabled: true // Support less embedded JS files}}},server: {
port: 9999./ / the port number
open: true.// Whether to open automatically in the browser
https: false.// Whether to enable HTTPS}})Copy the code
The following points also need to be noted: 2. Vite does not have built-in Less or Sass build dependencies. 3. @vitejs/plugin-vue applies only to VUe3. If you need to support Vue2, you need to install viet-plugin-vue2
Vite-ssr service configuration
Since the old project injected parameters to static pages based on Node, the SSR service was configured in addition. Create a new viteserver.js file in the build file to configure the vite server content and configure a new entry file based on the existing index.html file to start the command node build/ viteserver.js
Entrance to the configuration
// vite.html<! DOCTYPE html><html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<! -- Additional content to inject -->
<! --preload-links-->
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/vite/entry-client.js"></script>
</body>
</html>
Copy the code
Vue rendering mode changed
import { createSSRApp } from 'vue'
import App from '.. /App.vue'
import store from '@store/index'
export function createApp() {
const app = createSSRApp(App)
return { app, store }
}
Copy the code
Vite – SSR configuration
const fs = require('fs')
const express = require('express')
const path = require('path')
const { createServer: createViteServer } = require('vite')
async function createServer() {
const app = express()
// Create a Vite application in middleware mode, which disables vite's own HTML service logic
// And let the upper-level server take over control
const vite = await createViteServer({
logLevel: 'error'.server: {
middlewareMode: 'ssr'.watch: {
// During tests we edit the files too fast and sometimes chokidar
// misses change events, so enforce polling for consistency
usePolling: true.interval: 100}}})// Use vite's Connect instance as the middleware
app.use(vite.middlewares)
app.use('/render'.async (req, res) => {
/ / service index. HTML
res.setHeader('X-Frame-Options'.'allow-from *')
const url = req.originalUrl
const isSupportWebp = req.headers['accept'].toLowerCase().includes('image/webp')
try {
// 1. Read index.html
let template = fs.readFileSync( path.resolve(__dirname, '.. /src/vite/vite.html'), 'utf-8' )
// 2. Apply vite HTML conversion. This will inject the Vite HMR client,
// The HTML transformation is also applied from the Vite plug-in.
// For example: @vitejs/plugin-react-refresh global Preambles
template = await vite.transformIndexHtml(url, template)
// 4. Render the application's HTML. This assumes the 'render' of the entry-server.js export
// The function calls the appropriate SSR framework API.
/ / such as ReactDOMServer. RenderToString ()
const appScript = ``
Inject rendered application HTML into the template.
const html = template.replace(` `, appScript)
// 6. Return the rendered HTML.
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
} catch (e) {
// If an error is caught, have vite fix the stack so it can be mapped back to your actual source code.
vite.ssrFixStacktrace(e)
console.error(e)
res.status(500).end(e.message)
}
})
app.use(
express.static('/', {
extensions: ['html']}))return { app, vite }
}
createServer().then(({ app }) = > {
app.listen(7777.() = > { console.log('localhost:7777')})})Copy the code
conclusion
This article is mainly used to summarize the construction process of VITE + VUE. Since the author is also in the beginner stage of Vite, I hope you can put forward valuable opinions on any writing that is not rigorous. Vite Chinese version vue3 vant-V3