多彩编程 多彩编程MZPH · CODE BLOG
ARTICLE DETAIL

文章详情

深耕前端与后端开发技术的一线实战笔记与踩坑复盘。

vite配置

vite配置 #vite配置-------##这是项目初始化创建的时候配置vite.config.js import { defineConfig } from ‘vite’ import vue from ‘vitejs/plugin-vue’ // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], })接下来围绕vite.config.js对项目进行配置这里主要讲解用到比较常用的操作主要模块1、基础配置与环境变量2、插件配置3、开发服务器配置****4、打包配置### 1、基础配置与环境变量一下配置都在defineConfig下配置主要配置有root(源文件路径)、define全局常量、resolve模块解析、base(静态文件路径)等 import { defineConfig } from ‘vite’; import vue from ‘vitejs/plugin-vue’; import path from ‘path’; // 定义一个路径解析辅助函数 const resolvePath (relativePath) path.resolve(_dirname, relativePath); // 获取当前环境 const isDev process.env.NODE_ENV ! ‘production’; export default defineConfig({ // 项目根目录默认是配置文件所在目录根据需要可自定义 root: resolvePath(‘./’), // 应用的基路径影响资源和路由的基准URL base: isDev ? ‘/’ : ‘./’, // 静态资源目录存放不会通过 Vite 转换的静态资源 publicDir: ‘public’, // 环境变量前缀确保安全性和避免冲突 envPrefix: VITE’, // 定义全局常量用于环境变量注入或其他编译时替换 define: {APP_VERSION: JSON.stringify(process.env.npm_package_version), ‘process.env’: process.env, }, // 配置模块解析规则如别名简化导入路径 resolve: { alias: [ { find: ‘’, replacement: resolvePath(‘src’) }, ], extensions: [‘.js’, ‘.ts’, ‘.jsx’, ‘.tsx’, ‘.json’, ‘.vue’], }, // CSS配置包括预处理器设置等 css: { preprocessorOptions: { less: { modifyVars: { hack:true; import (reference) ${resolvePath(src/assets/css/variables.less)};, }, javascriptEnabled: true, }, }, }, //打包忽略的debug esbuild:{ drop: isDev ? [] : [“console”, “debugger”] }, // 依赖优化配置控制哪些依赖进行预构建等 optimizeDeps: { include: [‘vue’, ‘vue-router’], exclude: [‘lodash-es’], }, // 日志配置虽然未展示具体配置但可通过此选项调整日志输出 // logger: { … }, });### 2、插件配置plugins配置(这个模块主要是针对三方库的配置不用详细了解)库文件配置主要是如下两个参考npm | Home简介 | Rollup 中文文档主要用于安装库的运用导入包括打包库、图标库、以及各种格式优化等可以根据不同模式进行配置这里不区分开发和生产模式 import postcss from ‘rollup-plugin-postcss’;//压缩css import VitePluginDistZipJs from “vite-plugin-zip-dist”;//zip构建 import htmlMinifier from ‘html-minifier’;//html压缩 import viteImagemin from ‘vite-plugin-imagemin’//图片压缩 import AutoImport from ‘unplugin-auto-import/vite’//自动导入Vue和WebExtension Polyfill的相关功能 import copy from ‘rollup-plugin-copy’//文件复制 plugins: [ vue(), //Build zip mode() ‘development’ ? null : VitePluginDistZipJs( { zipName: ‘moolah-extension’ ‘-’ browser() ‘-’ mode() ‘.’ process.env.VITE_VERSION, dayjsFormat: ‘’, zipDir: r(‘dist’), } ), //compress css isDev ? null : postcss({ plugins: [], extract: ‘style.css’, minimize: true, }), //compress html { name: ‘html-minify’, transformIndexHtml(html) { return htmlMinifier.minify(html, { collapseWhitespace: true, // 折叠空白符将多余的空格和换行符折叠为一个空格 removeComments: true,// 删除 HTML 中的注释 minifyCSS: true,// 压缩内联 CSS minifyJS: true, // 压缩内联 JavaScript conservativeCollapse: true // 保守地折叠空白符仅在标签之间的空格会被折叠忽略元素内容中的空格 }); } }, //compress Img viteImagemin({ gifsicle: { optimizationLevel: 7, interlaced: false, }, optipng: { optimizationLevel: 7, }, mozjpeg: { quality: 20, }, pngquant: { quality: [0.8, 0.9], speed: 4, }, svgo: { plugins: [ { name: ‘removeViewBox’, }, { name: ‘removeEmptyAttrs’, active: false, }, ], }, }), AutoImport({ imports: [ “vue”, { ‘webextension-polyfill’: [ [‘‘, ‘browser’], ], }, ], }), // rewrite assets to use relative path-路径重写 { name: ‘assets-rewrite’, enforce: ‘post’, apply: ‘build’, transformIndexHtml(html, { path }) { return html.replace(//dist/assets//g,${relative(dirname(path), /assets)}/.replace(//g, ‘/’)) }, }, copy({ targets: [ { src: ‘src/assets’, dest:dist/${mode()}}, { src: ‘src/manifest.json’, dest:dist/${mode()}}, { src: ‘src/_locales’, dest:dist/${mode()}} ] }), ],### 3、开发服务器配置这个模块主要是配置服务器相关的配置请看代码包含了大部分配置不是每个配置都需要开启根据具体项目情况而定 server: { // 更改服务器监听的主机名使其在局域网内可访问 host: ‘0.0.0.0’, // 修改开发服务器的端口号 port: 8080, // 是否在服务器启动时自动打开浏览器 open: true, // 启用HTTPS服务需要提供证书和私钥的路径 https: { key: ‘/path/to/server.key’, cert: ‘/path/to/server.crt’, }, // 跨源资源共享配置允许所有源访问 cors: true, // 配置代理将 /api 开头的请求代理到 http://localhost:3001 proxy: { ‘/api’: { target: ‘http://localhost:3001’, changeOrigin: true, rewrite: (path) path.replace(/^/api/, ‘’), }, }, // 控制文件系统监视忽略监视 node_modules 目录 watch: { ignored: ‘**/node_modules’, }, // 当端口被占用时不自动寻找下一个可用端口而是直接报错 strictPort: false, // 热模块替换默认开启可根据需要关闭 hmr: true, },###4、打包配置这个主要是自己的打包build配置一般会结合上面的插件一起使用才能让build更便捷以下也是常用的配置实际根据具体项目而定 build: { // 输出目录构建产物将存放在此目录下默认为’dist’ outDir: ‘dist’, // 构建前是否清空输出目录默认为true emptyOutDir: true, // 指定构建目标的ECMAScript版本影响代码的转译程度默认为’es2020’ target: ‘es2020’, // 构建时是否进行代码压缩默认为true minify: true, // 当拆分的chunk大小超过此限制单位KB时发出警告默认为500KB chunkSizeWarningLimit: 500, // 构建后是否报告压缩后的文件大小默认为true reportCompressedSize: true, // 传递给Rollup的额外配置选项 rollupOptions: { // 输入配置可以定义多个入口点 input: { main: ‘src/main.js’, // 例如主入口文件 alternative: ‘src/alternative-entry.js’, // 另一个入口文件 }, // 输出配置可以自定义输出格式、文件名等 output: { // 例如修改输出文件名 entryFileNames: ‘[name].[hash].js’, }, }, // 服务器端渲染相关配置 ssr: { // SSR相关选项 }, // 小于该大小单位字节的资源会被内联到bundle中默认为4096字节 assetsInlineLimit: 4096, // 指定CSS构建的目标浏览器支持等级独立于’target’配置 cssTarget: ‘defaults’, // 是否为模块preload/prefetch添加polyfill默认为true polyfillModulePreload: true, // 配置如何处理CommonJS模块 commonjsOptions: { // 例如是否将混合模块转换为ESM transformMixedEsModules: true, }, // 是否在构建时生成manifest文件默认为true writeManifest: true, }, 完整配置如下由于有时候需要分开打包所以将公共部分抽离了 import { defineConfig } from “vite”; import vue from “vitejs/plugin-vue”; import { r, port, isDev, mode } from “./scripts/utils”; import { dirname, relative } from ‘node:path’ import AutoImport from ‘unplugin-auto-import/vite’ import copy from ‘rollup-plugin-copy’ import viteImagemin from ‘vite-plugin-imagemin’ import htmlMinifier from ‘html-minifier’; import postcss from ‘rollup-plugin-postcss’; import VitePluginDistZipJs from “vite-plugin-zip-dist”; export const sharedConfig { root: r(“src”), define: { ‘DEV’: isDev, ‘process.env’: process.env }, resolve: { alias: { “”: r(“src”), “~”: r(“src”), }, extensions: [“.js”, “.ts”, “.jsx”, “.tsx”, “.json”, “.vue”], }, esbuild:{ drop: isDev ? [] : [“console”, “debugger”] }, plugins: [ vue(), //Build zip mode() ‘development’ ? null : VitePluginDistZipJs( { zipName: ‘moolah-extension’ ‘-’ ‘-’ mode() ‘.’ process.env.VITE_VERSION, dayjsFormat: ‘’, zipDir: r(‘dist’), } ), //compress css isDev ? null : postcss({ plugins: [], extract: ‘style.css’, minimize: true, }), //compress html { name: ‘html-minify’, transformIndexHtml(html) { return htmlMinifier.minify(html, { collapseWhitespace: true, // 折叠空白符将多余的空格和换行符折叠为一个空格 removeComments: true,// 删除 HTML 中的注释 minifyCSS: true,// 压缩内联 CSS minifyJS: true, // 压缩内联 JavaScript conservativeCollapse: true // 保守地折叠空白符仅在标签之间的空格会被折叠忽略元素内容中的空格 }); } }, //compress Img viteImagemin({ gifsicle: { optimizationLevel: 7, interlaced: false, }, optipng: { optimizationLevel: 7, }, mozjpeg: { quality: 20, }, pngquant: { quality: [0.8, 0.9], speed: 4, }, svgo: { plugins: [ { name: ‘removeViewBox’, }, { name: ‘removeEmptyAttrs’, active: false, }, ], }, }), AutoImport({ imports: [ “vue”, { ‘webextension-polyfill’: [ [’, ‘browser’], ], }, ], }), // rewrite assets to use relative path { name: ‘assets-rewrite’, enforce: ‘post’, apply: ‘build’, transformIndexHtml(html, { path }) { return html.replace(/“/dist/assets//g,${relative(dirname(path), /assets)}/.replace(//g, ‘/’)) }, }, copy({ targets: [ { src: ‘src/assets’, dest:dist/${mode()}}, { src: ‘src/manifest.json’, dest:dist/${mode()}}, { src: ‘src/_locales’, dest:dist/${mode()}} ] }), ], } export default defineConfig(({ command }) ({ …sharedConfig, server: { port, hmr: { host: ‘localhost’, }, }, build: { outDir: r(dist/${mode()}), emptyOutDir: false, rollupOptions: { input: { options: r(“src/options/index.html”), popup: r(“src/popup/index.html”), }, }, terserOptions: { mangle: false, }, extensions: [”.js, “.ts”, “.jsx”, “.tsx”, “.json”, “.vue”], }, }));
返回列表