vue3+vite 打包去掉console和debugger控制台打印信息

vite 已经将这个功能内置了,所以我们只需要修改配置文件:vite.config.js即可,配置包括drop_console:去掉console信息,drop_debugger:去掉debugger信息。

前置条件是需要新增配置:

minify: 'terser'

 否则不起作用。

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import inject from '@rollup/plugin-inject'
import viteCompression from 'vite-plugin-compression'
// https://vitejs.dev/config/
export default defineConfig({
  base: "./",
  build: {
    minify: 'terser',
    terserOptions: {
        compress: {
            //生产环境时移除console
            drop_console: true,
            drop_debugger: true,
        }
    },
    rollupOptions: {
      output: {
        chunkFileNames: 'static/js/[name]-[hash].js',
        entryFileNames: 'static/js/[name]-[hash].js',
        assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        manualChunks(id) {
          //静态资源分拆打包
          if (id.includes("node_modules")) {
            return id
              .toString()
              .split("node_modules/")[1]
              .split("/")[0]
              .toString();
          }
        }
      }
    }
  },
  plugins: [
    vue(),
    inject({
      $: "jquery",  // 这里会自动载入 node_modules 中的 jquery
      jQuery: "jquery",
      "windows.jQuery": "jquery"
    }),
    //大文件压缩.gz
    viteCompression({
      verbose: true,
      disable: false,
      threshold: 10240,
      algorithm: 'gzip',
      ext: '.gz',
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  css:{
    preprocessorOptions:{
      less:{
        javascriptEnabled: true,  //注意,这一句是在less对象中,写在外边不起作用
      }
    }
  },
  server: {
    port: 5173,
    host: '0.0.0.0',
    proxy: {
      '/api': {
        target: '', //目标url https://api.openai.com/
        changeOrigin: true, //支持跨域
        rewrite: (path) => path.replace(/^\/api/, "") //重写路径,替换/api
        
      }
    },
    cors: true, // 配置 CORS
  }
})

 如果新增配置后报错:

[vite:terser] terser not found. Since Vite v3, terser has become an optional dependency. You need to install 

是因为缺少依赖文件:terser

直接使用命令安装即可解决:

npm install terser

猜你喜欢

转载自blog.csdn.net/weixin_39823006/article/details/130925346