🐲总有一个可以提升你工作效率的vite插件🐲

vite-plugin-rm-others-console

vite-plugin-rm-others-console用于在构建过程中删除控制台输出的日志信息(console.log、console.warn、console.error等)。这个插件可以帮助开发者在生产环境中减少不必要的日志输出,提高应用的性能和安全性。

安装使用

①安装

bash 复制代码
pnpm i vite-plugin-rm-others-console -D

②使用

js 复制代码
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import removeOthersConsole from 'vite-plugin-rm-others-console';
​
export default defineConfig({
  plugins: [
    removeOthersConsole(),
    // ... others
  ]
});

警告

1.不建议在生产环境使用

如果打包只会留下打包者的console.log语句,可能会影响其他开发者调试,虽然这是个坏习惯!

你可以根据据下面的例子使用vite官方方法drop所有console语句。

js 复制代码
//vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
​
export default defineConfig({
    plugins: [vue()],
    build: {
        minify: 'terser',
        terserOptions: {
            compress: {
                //生产环境时移除console
                drop_console: true,
                drop_debugger: true,
            },
        },
    },
})
  1. 请确保将处理的是最原始的文件

由于插件严格依赖行判读git作者,所以该插件需要确保在可能会修改源文件的插件之前执行。

plugin-web-update-notification

plugin-web-update-notification是一个用于在网页中显示更新通知或提示的插件。

通常情况下,这种插件会检测网页内容或者页面元素的变化,并在内容或元素更新时显示一个通知或提示框,让用户知道页面内容已经更新。

以 git commit hash (也支持 svn revision number、package.json version、build timestamp、custom) 为版本号,打包时将版本号写入 json 文件。客户端轮询服务器上的版本号(浏览器窗口的 visibilitychange、focus 事件辅助),和本地作比较,如果不相同则通知用户刷新页面。

安装

bash 复制代码
# vite
pnpm add @plugin-web-update-notification/vite -D
​
# umijs
pnpm add @plugin-web-update-notification/umijs -D
​
# webpack plugin
pnpm add @plugin-web-update-notification/webpack -D

Vite配置

基础使用

ts 复制代码
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { webUpdateNotice } from '@plugin-web-update-notification/vite'
​
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    webUpdateNotice({
      logVersion: true,
    }),
  ]
})

自定义通知栏文本

ts 复制代码
// vite.config.ts
export default defineConfig({
  plugins: [
    vue(),
    webUpdateNotice({
      notificationProps: {
        title: '标题',
        description: 'System update, please refresh the page',
        buttonText: '刷新',
        dismissButtonText: '忽略'
      },
    }),
  ]
})

国际化

ts 复制代码
// vite.config.ts
export default defineConfig({
  plugins: [
    vue(),
    webUpdateNotice({
      // plugin preset: zh_CN | zh_TW | en_US
      locale: "en_US",
      localeData: {
        en_US: {
          title: "📢 system update",
          description: "System update, please refresh the page",
          buttonText: "refresh",
          dismissButtonText: "dismiss",
        },
        zh_CN: {
          ...
        },
        ...
      },
    }),
  ],
});
​
​
// other file to set locale
window.pluginWebUpdateNotice_.setLocale('zh_CN')

取消默认的通知栏,监听更新事件自定义行为

ts 复制代码
// vite.config.ts
export default defineConfig({
  plugins: [
    vue(),
    webUpdateNotice({
      hiddenDefaultNotification: true
    }),
  ]
})
​
// 在其他文件中监听自定义更新事件
document.body.addEventListener('plugin_web_update_notice', (e) => {
  const { version, options } = e.detail
  // write some code, show your custom notification and etc.
  alert('System update!')
})

关键:禁用 index.html 缓存!!!

如果 index.html 存在缓存,可能刷新后,更新提示还会存在,所以需要禁用 index.html 的缓存。这也是 SPA 应用部署的一个最佳实践吧。

通过 nginx ,禁用缓存:

conf 复制代码
# nginx.conf
location / {
  index index.html index.htm;
​
  if ( $uri = '/index.html' ) { # disabled index.html cache
    add_header Cache-Control "no-cache, no-store, must-revalidate";
  }
​
  try_files $uri $uri/ /index.html;
}

直接通过 html meta 标签禁用缓存:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
​
  <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
  <meta http-equiv="Pragma" content="no-cache" />
  <meta http-equiv="Expires" content="0" />
​
</head>
</html>

jscpd

jscpd是一个用于检测和报告JavaScript和TypeScript项目中重复代码的工具。它可以帮助开发人员识别项目中存在的重复代码,并提供定制化的报告,以便于定位和解决代码重复问题。

要使用jscpd工具,你可以按照以下步骤进行:

  1. 首先,使用npm安装jscpd工具:

    bash 复制代码
    npm install -g jscpd
  2. 进入你的JavaScript或TypeScript项目的根目录,并运行以下命令来检测重复代码:

    bash 复制代码
    jscpd .
    // jscpd --pattern "src/**/*.js"

    这将在项目中进行重复代码检测,并生成相应的报告。你也可以根据需要在命令中指定特定的文件或目录进行检测。

  3. jscpd工具还支持不同的报告输出格式,例如文本、JSON、XML等。你可以通过指定--output参数来选择报告输出格式,如下所示:

    bash 复制代码
    jscpd . --output=json
  4. 检测完成后,你可以查看生成的报告,识别重复的代码块并采取适当措施来优化和重构代码,以减少重复性并提高代码质量。

  5. 检测完成后,可以根据代码对比来查看重复内容,进而降低代码重复率。

vite-plugin-restart

vite-plugin-restart 用于监听文件的更改并重新启动 Vite 开发服务器。这个插件可以在开发过程中提供自动重新启动开发服务器的功能,使开发流程更加高效。

使用

  1. 安装 vite-plugin-restart 插件:

    bash 复制代码
    npm i vite-plugin-restart -D # yarn add vite-plugin-restart -D
  2. 配置 Vite:在 Vite 配置文件中(一般是 vite.config.js)使用该插件。

    js 复制代码
    import { defineConfig } from 'vite';
    import viteRestart from 'vite-plugin-restart';
    ​
    export default defineConfig({
      // 其他配置
      plugins: [
        viteRestart()
      ]
    });
  3. 指定监视的文件 :可以在 restart() 函数中传入一个对象,指定需要监视的文件或文件夹。

    js 复制代码
    // vite.config.js
    import ViteRestart from 'vite-plugin-restart'
    ​
    export default {
      plugins: [
        ViteRestart({
          restart: [
            'my.config.[jt]s',
          ]
        })
      ],
    }

当名为 my.config.jsmy.config.ts 的文件发生更改时,vite-plugin-restart 将重新启动 Vite 开发服务器。

这种配置有助于指定特定文件更改时重新启动开发服务器的行为,使开发过程更加灵活和高效。

vite-plugin-svg-icons

vite-plugin-svg-icons 用于在 Vite 项目中轻松使用 SVG 图标。它可以将 SVG 图标转换为 Vue 组件或 React 组件,并在需要时自动引入。这使得在项目中使用 SVG 图标变得非常简单和方便。

使用

  1. 安装 vite-plugin-svg-icons
bash 复制代码
yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D
  1. 在你的 Vite 配置文件中(一般是 vite.config.js)引入并配置该插件:
js 复制代码
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
​
export default () => {
  return {
    plugins: [
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/icons')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',
​
        /**
         * 自定义插入位置
         * @default: body-last
         */
        inject?: 'body-last' | 'body-first'
​
        /**
         * custom dom id
         * @default: __svg__icons__dom__
         */
        customDomId: '__svg__icons__dom__',
      }),
    ],
  }
}
  • 在 src/main.ts 内引入注册脚本
js 复制代码
import 'virtual:svg-icons-register'

到这里 svg 雪碧图已经生成

React 方式注册组件

jsx 复制代码
/src/components/SvgIcon.jsx
export default function SvgIcon({
  name,
  prefix = 'icon',
  color = '#333',
  ...props
}) {
  const symbolId = `#${prefix}-${name}`
​
  return (
    <svg {...props} aria-hidden="true">
      <use href={symbolId} fill={color} />
    </svg>
  )
}

vite-plugin-purgecss

vite-plugin-purgecss 用于在构建时移除项目中未使用的 CSS 样式,从而减少最终生成的 CSS 文件大小。这可以帮助提高项目的性能和加载速度。

在前端项目中,通常会使用一些 CSS 框架或者库,例如 Bootstrap、Tailwind CSS 等,这些框架包含了大量的 CSS 样式,但我们可能只使用其中的一小部分。未使用的 CSS 样式会增加文件大小,影响页面加载速度,因此需要将未使用的 CSS 移除掉。

vite-plugin-purgecss 就是为了解决这个问题而创建的。它会分析项目中的 HTML、JavaScript 文件,并根据实际使用的 CSS 类和选择器来移除未使用的 CSS 样式,从而减小构建后的 CSS 文件大小。

使用

  1. 安装 vite-plugin-purgecss 插件:

    bash 复制代码
    npm install vite-plugin-purgecss --save-dev
    // 或者
    yarn add vite-plugin-purgecss --dev
  2. 配置 Vite:在 Vite 配置文件中(一般是 vite.config.js)使用该插件。

    js 复制代码
    // vite.config.js
    import { defineConfig } from 'vite';
    import purgecss from 'vite-plugin-purgecss';
    ​
    export default defineConfig({
      // other Vite config
      plugins: [
        // other plugins
        purgecss()
      ]
    });
  3. 指定需要处理的文件 :可以在 purgecss() 函数中传入一个对象,指定需要处理的文件或文件夹。

    js 复制代码
    // vite.config.js
    import { defineConfig } from 'vite';
    import purgecss from 'vite-plugin-purgecss';
    ​
    export default defineConfig({
      // other Vite config
      plugins: [
        // other plugins
        purgecss({
          content: ['./index.html', './src/**/*.vue', './src/**/*.js']
        })
      ]
    });

这样,当项目构建时,vite-plugin-purgecss 会自动分析指定的文件,移除未使用的 CSS 样式,生成优化后的 CSS 文件。

vite-plugin-compression

vite-plugin-compression用于在构建应用程序时对静态资源进行gzip 或 brotli 压缩。这可以帮助减小文件大小,提高页面加载速度。

使用

  1. 安装 vite-plugin-compression
bash 复制代码
npm install vite-plugin-compression --save-dev
  1. vite.config.js 文件中引入插件并进行配置:
js 复制代码
import { defineConfig } from 'vite';
import compressionPlugin from 'vite-plugin-compression';
​
export default defineConfig({
  plugins: [
    compressionPlugin({
      // 配置压缩算法和文件类型
      algorithm: 'gzip', // 支持 'gzip', 'brotli'
      ext: '.gz', // 压缩文件的扩展名
      threshold: 10240, // 文件大小阈值,只有当文件大小大于这个值时才会被压缩,单位为字节,默认为 10240(即 10KB)
      deleteOriginFile: false // 是否删除原始文件,默认为 false,即保留原始文件
    })
  ]
});
  1. 现在,在构建应用程序时,vite-plugin-compression 将自动对指定类型的静态资源进行 gzip 或 brotli 压缩。
相关推荐
GISer_Jing2 小时前
前端面试通关:Cesium+Three+React优化+TypeScript实战+ECharts性能方案
前端·react.js·面试
落霞的思绪3 小时前
CSS复习
前端·css
咖啡の猫5 小时前
Shell脚本-for循环应用案例
前端·chrome
百万蹄蹄向前冲7 小时前
Trae分析Phaser.js游戏《洋葱头捡星星》
前端·游戏开发·trae
朝阳5818 小时前
在浏览器端使用 xml2js 遇到的报错及解决方法
前端
GIS之路8 小时前
GeoTools 读取影像元数据
前端
ssshooter9 小时前
VSCode 自带的 TS 版本可能跟项目TS 版本不一样
前端·面试·typescript
Jerry9 小时前
Jetpack Compose 中的状态
前端
dae bal10 小时前
关于RSA和AES加密
前端·vue.js
柳杉10 小时前
使用three.js搭建3d隧道监测-2
前端·javascript·数据可视化