Vite2.0 pit treading record
Is a supplement to the last article, recorded some problems encountered in the configuration project, I hope to help you ~
Vite project construction optimization
-
Dynamic route import after rollup construction, the dynamically imported files will generate asynchronous chunk files, which will be loaded on demand when we visit the project, greatly improving the loading speed of the application
import Home from '@/views/home/index.vue' import Layout from '@/components/Layout.vue' const routes: Array<RouteRecordRaw> = [ { path: '/'.component: Layout, redirect: '/home'.children: [{path: '/home'.name: 'Home'.component: Home, meta: { title: 'home'}}, {path: '/about'.name: 'About'.meta: { title: 'about'.keepAlive: true }, component: () = > import('@/views/about/index.vue')}, {path: '/square'.name: 'Square'.meta: { title: 'Component square'.keepAlive: true }, component: () = > import('@/views/square/index.vue'}]}]const router = createRouter({ history: process.env.NODE_ENV === 'development' ? createWebHistory(process.env.BASE_URL) : createWebHashHistory(process.env.BASE_URL), routes, scrollBehavior(to, from, savedPosition) { if (savedPosition) { // This is triggered when you go through the background return savedPosition } else { return { top: 0.behavior: 'smooth' } } } }) router.beforeEach((to, from, next) = > { // You can do some checking on permissions if(to.path ! = =from.path) { document.title = ` star ring |${to.meta.title}` } next() }) router.onError((error) = > { const pattern = /Loading chunk (\d)+ failed/g const isChunkLoadFailed = error.message.match(pattern) if (isChunkLoadFailed) { location.reload() } }) export default router Copy the code
The above code is a Router file for a Vue project built by Vite, using [email protected]. Vue Router supports dynamic imports out of the box, which means you can use dynamic imports instead of static imports. You can see in the code that both the About and Square pages are dynamically imported. MDN has a very detailed description of dynamic imports: portals
After rollup construction, the dynamically imported files will generate asynchronous chunk files, which will be loaded on demand when we visit the project, greatly improving the loading speed of the application.
The pit I stepped on in the dynamic route import in the Vite project:
@/ aliases are not supported at build time. At build time, the rollup build cannot find the corresponding file according to the configured alias, so an error will be reported during the build
Solution:
-
At first it felt like a reference path problem, so I tried several references, and finally one worked! Component: () = > import (‘/SRC/views/about/index. The vue ‘) to an absolute path, can normal boot
-
Upgrade the Vite version, starting with [email protected], without aliases. It is supported after upgrading to [email protected]. It is estimated that 2.0 is just out, and it is understandable that there is no perfect writing all of a sudden
-
Use the import.meta.glob method
I configured some of the errors and warnings encountered
warning: “import.meta” is not available in the configured target environment (“es2019”) and will be empty
This warning is generated when the vite configuration item esbuild.target is set to ‘ES2019’. Indicates that the import.meta API is not supported in this case
[vite] Internal server error: Invalid glob import syntax: pattern must start with “.” or “/” (relative to project root)
The arguments in import.meta.glob() must start with a “.” or a “/” to match the root directory
Final writing part of the code:
import Layout from '@/components/Layout.vue' const modules = import.meta.glob('/src/views/*/index.vue') const routes: Array<RouteRecordRaw> = [ { path: '/'.component: Layout, redirect: '/home'.children: [{path: '/home'.name: 'Home'.component: modules['/src/views/home/index.vue'].meta: { title: 'home'}}, {path: '/about'.name: 'About'.meta: { title: 'about'.keepAlive: true }, component: modules['/src/views/about/index.vue'] {},path: '/square'.name: 'Square'.meta: { title: 'Component square'.keepAlive: true }, component: modules['/src/views/square/index.vue']}]}Copy the code
By using the import.meta.glob method, we can configure routing through the background interface and control permissions. If the routes data is returned by the interface, the component that is not within the permission scope will not generate the route entry at all, which undoubtedly increases the power of permission control.
-
-
Configure build. RollupOptions. ManualChunks, subcontract the node_modules files loaded
manualChunks(id) { if (id.includes('node_modules') && id.includes('prime')) { return 'prime' } else if (id.includes('node_modules') && id.includes('vue')) { return 'vue' } else if (id.includes('node_modules')) { return 'vendor'}}Copy the code
If not, Vite packs the node_modules package into a large asynchronous vendor.js file, which increases the blocking time of page rendering if the file is too large. And it’s not conducive to page cache optimization. In the configuration above, I packaged the UI framework (primeVue) and vUe-related packages into a single file, which in addition to reducing the size of each dependent file, optimized the project cache. These dependency packages, such as base libraries, will be updated less often. Combined with the configuration of the file cache policy on the server, users can directly read the dependent files from the cache except for the first access and subsequent access. Cutting up the dependent file code can greatly improve the performance of a project.
Also, vite automatically generates the following HTML files when it is built
<! DOCTYPEhtml> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" href="/favicon.ico" /> <meta name="viewport" content="Width = device - width, initial - scale = 1.0" /> <title>My project</title> <script type="module" crossorigin src="/assets/index.e3627129.js"></script> <link rel="modulepreload" href="/js/vue/vue.a1ee204f.js"> <link rel="modulepreload" href="/js/prime/prime.eb4bfea6.js"> <link rel="stylesheet" href="/assets/prime.296674d4.css"> <link rel="stylesheet" href="/assets/index.289426b3.css"> </head> <body> <div id="app"></div> </body> </html> Copy the code
The link tag rel=” modulePreload “can be used to preload native modules, ensuring that certain files do not have to be loaded at execution time and also improving page performance
-
Image resource file processing. A resource smaller than the value of the assetsInlineLimit option is inlined as a Base64 data URL and packaged together into the file that references it. This reduces the number of file requests and improves project performance
other
- Place the asynchronous chunk generated by the dynamic import file in the corresponding folder, or customize the name of the chunk.
After checking the rollup file for a long time and trying for a while, I finally succeeded. Refer to the following configuration:
export default defineConfig({
build: {
assetsDir: 'assets'.rollupOptions: {
output: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
chunkFileNames: (chunkInfo: any) = > {
const facadeModuleId = chunkInfo.facadeModuleId ? chunkInfo.facadeModuleId.split('/') : []
const fileName = facadeModuleId[facadeModuleId.length - 2] | |'[name]'
return `js/${fileName}/[name].[hash].js`},}}}})Copy the code
-
The vite configuration passes in global SCSS variables
Configuration is as follows
export default defineConfig({ css: { preprocessorOptions: { scss: { additionalData: '@import "./src/styles/variables"; '}}}})Copy the code
-
It is also important to note that there are some differences between vite versions, so if you have a problem configuring your project according to the documentation, you may want to check if your version is not the same as the documentation.
The last
Share my configured vite2.0+Vue3.0 project: portal, used to test the waters of the project, if anything wrong, welcome to correct!