#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"],
- },
- }));
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |