Vite + Vue3 + Ts 解决打包生成的index.html页面显示空白、资源跨域、找不到资源、404-Page Not Found等错误;关于vite build后访问报错

一.vite.config.ts配置:主要的就是base: env.VITE_MODE === 'production' ? './' : '/',

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue';
import path from "path";
import { resolve } from 'path'
const port = 8080;
const host = "0.0.0.0";
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, __dirname)
  return {
    plugins: [
      vue(),
    ],
    base: env.VITE_MODE === 'production' ? './' : '/',
    resolve: {
      alias: {
        //resolve.alias设置别称 解决@绝对路径引入问题
        "@": path.resolve(__dirname, 'src'),
        "@assets": path.resolve(__dirname, "src/assets"),
        "@components": path.resolve(__dirname, "src/components"),
        "@images": path.resolve(__dirname, "src/assets/images"),
        "@views": path.resolve(__dirname, "src/views"),
        "@store": path.resolve(__dirname, "src/store"),
      },
    },
    css: {
      // css预处理器
      preprocessorOptions: {
        less: {
          modifyVars: {
            // 全局less变量存储路径(配置less的全局变量)
            hack: `true; @import (reference) "${resolve('src/public/config.less')}";`,
          },
          javascriptEnabled: true,
        }
      }
    },
    build: {
      outDir: "dist",
      assetsDir: "assets", //指定静态资源存放路径
      sourcemap: false, //是否构建source map 文件
      // terserOptions: {
      //   // 生产环境移除console
      //   compress: {
      //     drop_console: true,
      //     drop_debugger: true,
      //   },
      // },
    },
    server: {
      https: false, // 是否开启 https
      open: true, // 是否自动在浏览器打开
      port: port, // 端口号
      host: host,
      proxy: {
        "/api": {
          target: env.VITE_RES_URL, // 后台接口
          changeOrigin: true,
          secure: false, // 如果是https接口,需要配置这个参数
          ws: true, //websocket支持
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
  }
})

二. 打包后的结果如图所示,文件路径是./ 其实 去掉./是可以的,但是打包后是/favicon.ico这种路径是访问不到的,参考第一部分

三. 配置路由:路由改成 createWebHashHistory 

 四. vscode安装Live Server 

 

关于vite build后访问报错:Expected a JavaScript module script but the server responded with a MIME type of “

部署到线上时,页面一刷新就会报上述错误,百度了半天也没解决,参考了这个大佬的文章,写的很详细,跟着步骤做也是可以解决报错的!

下面说一下我的解决方式 :

 1. base 设置成 './'   

 2. 路由模式改成 createWebHashHistory即可

 Tips:参考了好多大佬写的,有的把base './'  改成 '/'的 不过我改成 '/' 资源路径不对还是白屏,跟着配置一圈没解决,无意中把路由模式 createWebHistory 改成 createWebHashHistory 就解决了问题!白屏也跟Nginx有关。欢迎各位大佬批评指正与补充!

猜你喜欢

转载自blog.csdn.net/qq_44535402/article/details/125894321