ToB企服应用市场:ToB评测及商务社交产业平台

标题: vite设置 [打印本页]

作者: 大连密封材料    时间: 2024-9-6 22:20
标题: vite设置
#vite设置

    ##这是项目初始化创建的时候设置(vite.config.js):
  1. import { defineConfig } from 'vite'
  2. import vue from '@vitejs/plugin-vue'
  3. // https://vitejs.dev/config/
  4. export default defineConfig({
  5.   plugins: [vue()],
  6. })
复制代码
接下来围绕vite.config.js对项目进行设置(这里主要解说用到比较常用的操纵):
        主要模块:
                    1、底子设置与环境变量
                    2、插件设置
                    3、开发服务器设置
                    4、打包设置
  1、底子设置与环境变量

        一下设置都在defineConfig下设置:
主要设置有:root(源文件路径)、define(全局常量)、resolve(模块剖析)、base(静态文件路径)等
  1. import { defineConfig } from 'vite';
  2. import vue from '@vitejs/plugin-vue';
  3. import path from 'path';
  4. // 定义一个路径解析辅助函数
  5. const resolvePath = (relativePath) => path.resolve(__dirname, relativePath);
  6. // 获取当前环境
  7. const isDev = process.env.NODE_ENV !== 'production';
  8. export default defineConfig({
  9.   // 项目根目录,默认是配置文件所在目录,根据需要可自定义
  10.   root: resolvePath('./'),
  11.   // 应用的基路径,影响资源和路由的基准URL
  12.   base: isDev ? '/' : './',
  13.   // 静态资源目录,存放不会通过 Vite 转换的静态资源
  14.   publicDir: 'public',
  15.   // 环境变量前缀,确保安全性和避免冲突
  16.   envPrefix: 'VITE_',
  17.   // 定义全局常量,用于环境变量注入或其他编译时替换
  18.   define: {
  19.     __APP_VERSION__: JSON.stringify(process.env.npm_package_version),
  20.     'process.env': process.env,
  21.   },
  22.   // 配置模块解析规则,如别名,简化导入路径
  23.   resolve: {
  24.     alias: [
  25.       { find: '@', replacement: resolvePath('src') },
  26.     ],
  27.     extensions: ['.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
  28.   },
  29.   // CSS配置,包括预处理器设置等
  30.   css: {
  31.     preprocessorOptions: {
  32.       less: {
  33.         modifyVars: {
  34.           hack: `true; @import (reference) "${resolvePath('src/assets/css/variables.less')}";`,
  35.         },
  36.         javascriptEnabled: true,
  37.       },
  38.     },
  39.   },
  40.     //打包忽略的debug
  41.     esbuild:{
  42.       drop: isDev ? [] : ["console", "debugger"]
  43.     },
  44.   // 依赖优化配置,控制哪些依赖进行预构建等
  45.   optimizeDeps: {
  46.     include: ['vue', 'vue-router'],
  47.     exclude: ['lodash-es'],
  48.   },
  49.   // 日志配置,虽然未展示具体配置,但可通过此选项调整日志输出
  50.   // logger: { ... },
  51. });
复制代码

2、插件设置

plugins设置(这个,模块主要是针对三方库的设置,不用具体了解):
库文件设置主要是如下两个(参考):
npm | Home
简介 | Rollup 中文文档
主要用于安装库的运用导入(包括打包库、图标库、以及各种格式优化等)可以根据差异模式进行设置,这里不区分开发和生产模式:
  1. import postcss from 'rollup-plugin-postcss';//压缩css
  2. import VitePluginDistZipJs from "vite-plugin-zip-dist";//zip构建
  3. import htmlMinifier from 'html-minifier';//html压缩
  4. import viteImagemin from 'vite-plugin-imagemin'//图片压缩
  5. import AutoImport from 'unplugin-auto-import/vite'//自动导入Vue和WebExtension Polyfill的相关功能
  6. import copy from 'rollup-plugin-copy'//文件复制
  7.     plugins: [
  8.         vue(),
  9.         //Build zip
  10.         mode() === 'development' ? null : VitePluginDistZipJs(
  11.           {
  12.             zipName: 'moolah-extension'  + '-' + browser()  + '-' + mode() + '.' + process.env.VITE_VERSION,
  13.             dayjsFormat: '',
  14.             zipDir: r('dist'),
  15.           }
  16.         ),
  17.         //compress css
  18.        isDev ? null : postcss({
  19.           plugins: [],
  20.           extract: 'style.css',
  21.           minimize: true,
  22.         }),
  23.         //compress html
  24.         {
  25.           name: 'html-minify',
  26.           transformIndexHtml(html) {
  27.             return htmlMinifier.minify(html, {
  28.               collapseWhitespace: true, // 折叠空白符,将多余的空格和换行符折叠为一个空格
  29.               removeComments: true,// 删除 HTML 中的注释
  30.               minifyCSS: true,// 压缩内联 CSS
  31.               minifyJS: true, // 压缩内联 JavaScript
  32.               conservativeCollapse: true // 保守地折叠空白符,仅在标签之间的空格会被折叠,忽略元素内容中的空格
  33.             });
  34.           }
  35.         },
  36.         //compress Img
  37.         viteImagemin({
  38.           gifsicle: {
  39.             optimizationLevel: 7,
  40.             interlaced: false,
  41.           },
  42.           optipng: {
  43.             optimizationLevel: 7,
  44.           },
  45.           mozjpeg: {
  46.             quality: 20,
  47.           },
  48.           pngquant: {
  49.             quality: [0.8, 0.9],
  50.             speed: 4,
  51.           },
  52.           svgo: {
  53.             plugins: [
  54.               {
  55.                 name: 'removeViewBox',
  56.               },
  57.               {
  58.                 name: 'removeEmptyAttrs',
  59.                 active: false,
  60.               },
  61.             ],
  62.           },
  63.         }),
  64.         AutoImport({
  65.             imports: [
  66.                 "vue",
  67.                 {
  68.                     'webextension-polyfill': [
  69.                         ['*', 'browser'],
  70.                     ],
  71.                 },
  72.             ],
  73.         }),
  74.          // rewrite assets to use relative path-路径重写
  75.         {
  76.             name: 'assets-rewrite',
  77.             enforce: 'post',
  78.             apply: 'build',
  79.             transformIndexHtml(html, { path }) {
  80.                 return html.replace(/"\/dist\/assets\//g, `"${relative(dirname(path), '/assets')}/`.replace(/\\/g, '/'))
  81.             },
  82.         },
  83.         copy({
  84.             targets: [
  85.               { src: 'src/assets', dest: `dist/${mode()}` },
  86.               { src: 'src/manifest.json', dest: `dist/${mode()}` },
  87.               { src: 'src/_locales', dest: `dist/${mode()}` }
  88.             ]
  89.         }),
  90.     ],
复制代码
      3、开发服务器设置

        这个模块主要是设置服务器相干的,设置请看代码(包罗了大部门设置,不是每个设置都需要开启,根据具体项目环境而定):
  1.   server: {
  2.     // 更改服务器监听的主机名,使其在局域网内可访问
  3.     host: '0.0.0.0',
  4.    
  5.     // 修改开发服务器的端口号
  6.     port: 8080,
  7.     // 是否在服务器启动时自动打开浏览器
  8.     open: true,
  9.     // 启用HTTPS服务,需要提供证书和私钥的路径
  10.     https: {
  11.       key: '/path/to/server.key',
  12.       cert: '/path/to/server.crt',
  13.     },
  14.     // 跨源资源共享配置,允许所有源访问
  15.     cors: true,
  16.     // 配置代理,将 /api 开头的请求代理到 http://localhost:3001
  17.     proxy: {
  18.       '/api': {
  19.         target: 'http://localhost:3001',
  20.         changeOrigin: true,
  21.         rewrite: (path) => path.replace(/^\/api/, ''),
  22.       },
  23.     },
  24.     // 控制文件系统监视,忽略监视 node_modules 目录
  25.     watch: {
  26.       ignored: '**/node_modules',
  27.     },
  28.     // 当端口被占用时,不自动寻找下一个可用端口,而是直接报错
  29.     strictPort: false,
  30.     // 热模块替换,默认开启,可根据需要关闭
  31.     hmr: true,
  32.   },
复制代码
        4、打包设置

        这个主要是自己的打包build设置,一样平常会联合上面的插件一起使用,才能让build更便捷:
        以下也是常用的设置(实际根据具体项目而定)
  1.   build: {
  2.     // 输出目录,构建产物将存放在此目录下,默认为'dist'
  3.     outDir: 'dist',
  4.     // 构建前是否清空输出目录,默认为true
  5.     emptyOutDir: true,
  6.     // 指定构建目标的ECMAScript版本,影响代码的转译程度,默认为'es2020'
  7.     target: 'es2020',
  8.     // 构建时是否进行代码压缩,默认为true
  9.     minify: true,
  10.     // 当拆分的chunk大小超过此限制(单位:KB)时发出警告,默认为500KB
  11.     chunkSizeWarningLimit: 500,
  12.     // 构建后是否报告压缩后的文件大小,默认为true
  13.     reportCompressedSize: true,
  14.     // 传递给Rollup的额外配置选项
  15.     rollupOptions: {
  16.       // 输入配置,可以定义多个入口点
  17.       input: {
  18.         main: 'src/main.js', // 例如,主入口文件
  19.         alternative: 'src/alternative-entry.js', // 另一个入口文件
  20.       },
  21.       // 输出配置,可以自定义输出格式、文件名等
  22.       output: {
  23.         // 例如,修改输出文件名
  24.         entryFileNames: '[name].[hash].js',
  25.       },
  26.     },
  27.     // 服务器端渲染相关配置
  28.     ssr: {
  29.       // SSR相关选项
  30.     },
  31.     // 小于该大小(单位:字节)的资源会被内联到bundle中,默认为4096字节
  32.     assetsInlineLimit: 4096,
  33.     // 指定CSS构建的目标浏览器支持等级,独立于'target'配置
  34.     cssTarget: 'defaults',
  35.     // 是否为模块preload/prefetch添加polyfill,默认为true
  36.     polyfillModulePreload: true,
  37.     // 配置如何处理CommonJS模块
  38.     commonjsOptions: {
  39.       // 例如,是否将混合模块转换为ESM
  40.       transformMixedEsModules: true,
  41.     },
  42.     // 是否在构建时生成manifest文件,默认为true
  43.     writeManifest: true,
  44.   },
复制代码
完整设置如下:
由于偶然候需要分开打包,所以将公共部门抽离了:
  1. import { defineConfig } from "vite";
  2. import vue from "@vitejs/plugin-vue";
  3. import { r, port, isDev, mode } from "./scripts/utils";
  4. import { dirname, relative } from 'node:path'
  5. import AutoImport from 'unplugin-auto-import/vite'
  6. import copy from 'rollup-plugin-copy'
  7. import viteImagemin from 'vite-plugin-imagemin'
  8. import htmlMinifier from 'html-minifier';
  9. import postcss from 'rollup-plugin-postcss';
  10. import VitePluginDistZipJs from "vite-plugin-zip-dist";
  11. export const sharedConfig = {
  12.     root: r("src"),
  13.     define: {
  14.         '__DEV__': isDev,
  15.         'process.env': process.env
  16.     },
  17.     resolve: {
  18.         alias: {
  19.             "@": r("src"),
  20.             "~@": r("src"),
  21.         },
  22.         extensions: [".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
  23.     },
  24.     esbuild:{
  25.       drop: isDev ? [] : ["console", "debugger"]
  26.     },
  27.     plugins: [
  28.         vue(),
  29.         //Build zip
  30.         mode() === 'development' ? null : VitePluginDistZipJs(
  31.           {
  32.             zipName: 'moolah-extension'  + '-' + '-' + mode() + '.' + process.env.VITE_VERSION,
  33.             dayjsFormat: '',
  34.             zipDir: r('dist'),
  35.           }
  36.         ),
  37.         //compress css
  38.        isDev ? null : postcss({
  39.           plugins: [],
  40.           extract: 'style.css',
  41.           minimize: true,
  42.         }),
  43.         //compress html
  44.         {
  45.           name: 'html-minify',
  46.           transformIndexHtml(html) {
  47.             return htmlMinifier.minify(html, {
  48.               collapseWhitespace: true, // 折叠空白符,将多余的空格和换行符折叠为一个空格
  49.               removeComments: true,// 删除 HTML 中的注释
  50.               minifyCSS: true,// 压缩内联 CSS
  51.               minifyJS: true, // 压缩内联 JavaScript
  52.               conservativeCollapse: true // 保守地折叠空白符,仅在标签之间的空格会被折叠,忽略元素内容中的空格
  53.             });
  54.           }
  55.         },
  56.         //compress Img
  57.         viteImagemin({
  58.           gifsicle: {
  59.             optimizationLevel: 7,
  60.             interlaced: false,
  61.           },
  62.           optipng: {
  63.             optimizationLevel: 7,
  64.           },
  65.           mozjpeg: {
  66.             quality: 20,
  67.           },
  68.           pngquant: {
  69.             quality: [0.8, 0.9],
  70.             speed: 4,
  71.           },
  72.           svgo: {
  73.             plugins: [
  74.               {
  75.                 name: 'removeViewBox',
  76.               },
  77.               {
  78.                 name: 'removeEmptyAttrs',
  79.                 active: false,
  80.               },
  81.             ],
  82.           },
  83.         }),
  84.         AutoImport({
  85.             imports: [
  86.                 "vue",
  87.                 {
  88.                     'webextension-polyfill': [
  89.                         ['*', 'browser'],
  90.                     ],
  91.                 },
  92.             ],
  93.         }),
  94.          // rewrite assets to use relative path
  95.         {
  96.             name: 'assets-rewrite',
  97.             enforce: 'post',
  98.             apply: 'build',
  99.             transformIndexHtml(html, { path }) {
  100.                 return html.replace(/"\/dist\/assets\//g, `"${relative(dirname(path), '/assets')}/`.replace(/\\/g, '/'))
  101.             },
  102.         },
  103.         copy({
  104.             targets: [
  105.               { src: 'src/assets', dest: `dist/${mode()}` },
  106.               { src: 'src/manifest.json', dest: `dist/${mode()}` },
  107.               { src: 'src/_locales', dest: `dist/${mode()}` }
  108.             ]
  109.         }),
  110.     ],
  111. }
  112. export default defineConfig(({ command }) => ({
  113.     ...sharedConfig,
  114.     server: {
  115.       port,
  116.       hmr: {
  117.         host: 'localhost',
  118.       },
  119.     },
  120.     build: {
  121.         outDir: r(`dist/${mode()}`),
  122.         emptyOutDir: false,
  123.         rollupOptions: {
  124.             input: {
  125.                 options: r("src/options/index.html"),
  126.                 popup: r("src/popup/index.html"),
  127.             },
  128.         },
  129.         terserOptions: {
  130.             mangle: false,
  131.         },
  132.         extensions: [".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
  133.     },
  134. }));
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4