vite+vue3+ssg+js打包时遇到的问题及解决

用到的插件 

window is not defined

document is not defined

if (typeof window != void 0) {
        window.open('http://localhost:8080/home?token=' + state.token + '¶ms=' + window.btoa(JSON.stringify(response.data)));
    }

如上图所示 可以在使用之前进行判断

vite.config.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import ElementPlus from 'unplugin-element-plus/vite'
import viteCompression from 'vite-plugin-compression'
import { fileURLToPath, URL } from 'url'
export default defineConfig({
  plugins: [
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
      extensions: ['vue', 'md']
    }),
    ElementPlus({
      useSource: true
    }),
    viteCompression({
      verbose: true,//默认即可
      disable: false,//开启压缩(不禁用),默认即可
      deleteOriginFile: false,//删除源文件
      threshold: 10240,//压缩前最小文件大小
      algorithm: 'gzip',//压缩算法
      ext: '.gz',//文件类型
    })
  ],
  optimizeDeps: {
    exclude: ['workbox-window'],
  },
  ssgOptions: {
    script: 'async',
    formatting:'none',
    // onFinished(){
    //   generateSitemap()
    // }
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('src', import.meta.url)),
    }
  },
  build: {
    target: 'modules',
    outDir: 'dist',
    // minify:'terser',
    assetsDir: 'assets',//指定生成静态资源的存放路径
    cssCodeSplit: true,//如果设置为false,整个项目中的所有css会被提取到一个css文件中去
    terserOptions: {
      compress: {
        drop_console: true,//打包时删除console
        drop_debugger: true,//打包时删除debugger
        pure_funcs: ['console.log'],
      },
      output: {
        //去掉注释内容
        comments: true,
      },
    },
    rollupOptions: {
      minify: 'terser',//混淆器。terser构建后文件体积更小
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return id.toString().split('node_modules/')[1].split('/')[0].toString();
          }
        }
      }
    }
  },
  ssr: {
    noExternal: ['element-plus'],
  },
})

main.js

import { ViteSSG } from 'vite-ssg'
import App from './App.vue'
import { routes } from './router/index'
import { store } from './store';
import network from './common/network.js'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

import mitt from 'mitt';
import { AES_Encrypt, AES_Decrypt } from './utils/aes.js'
import VueLazyload from "vue-lazyload";
import './style.css'
// import 'vue3-video-play/dist/style.css'
// import {videoPlay} from 'vue3-video-play';
import videos from './components/video.vue'
export const createApp = ViteSSG(
    App,
    { routes },
    ({ app, isClient, router, initialState }) => {
        app.config.globalProperties.$datas = network;
        app.config.globalProperties.$mitt = mitt();
        app.config.globalProperties.$AES_Encrypt = AES_Encrypt //全局加密
        app.config.globalProperties.$AES_Decrypt = AES_Decrypt //全局解密
        app.use(store)
        app.use(VueLazyload);
        app.component('videos',videos)
        for (let iconName in ElementPlusIconsVue) {
            app.component(iconName, ElementPlusIconsVue[iconName])
        }
        if (isClient) {
            //在客户端的时候注册videoPlay组件 防止window is not defined
            // app.component('videoPlay', videoPlay)
            router.beforeEach((to, from, next) => {
                //路由发生变化修改页面title
                if (to.meta.title) {
                    console.log("router.beforeEach----meta打印");
                    console.log(to.meta);
                    document.title = to.meta.title;
                    document.querySelector('meta[name="keywords"]').setAttribute('content', to.meta.keyword);
                    document.querySelector('meta[name="description"]').setAttribute('content', to.meta.description);
                }
                next()
            })
        }
    },
)

 isClient可以判断是否是客户端,在这里面使用window和document不会报错

在package.json

"scripts": {
    "dev": "vite --mode development",
    "pro": "vite --mode production",
    "build:dev": "vite build --mode development",
    "build": "vite-ssg build",
    "preview": "vite preview"
  },

打包过程中会遇到个别插件或者包中含有window报错 可以试着更换插件

我在其中使用了vue3-video-play报错 window is not defined 更换插件为video.js报错解决





  
  
  
  

npm i video.js
npm i videojs-contrib-hls

vite-ssg 问题​​​​​​​ 

你可能感兴趣的:(前端,javascript,vue.js)