当前位置:   article > 正文

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

vite打包后直接打开html 空白

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

  1. import { defineConfig, loadEnv } from 'vite'
  2. import vue from '@vitejs/plugin-vue';
  3. import path from "path";
  4. import { resolve } from 'path'
  5. const port = 8080;
  6. const host = "0.0.0.0";
  7. export default defineConfig(({ mode }) => {
  8. const env = loadEnv(mode, __dirname)
  9. return {
  10. plugins: [
  11. vue(),
  12. ],
  13. base: env.VITE_MODE === 'production' ? './' : '/',
  14. resolve: {
  15. alias: {
  16. //resolve.alias设置别称 解决@绝对路径引入问题
  17. "@": path.resolve(__dirname, 'src'),
  18. "@assets": path.resolve(__dirname, "src/assets"),
  19. "@components": path.resolve(__dirname, "src/components"),
  20. "@images": path.resolve(__dirname, "src/assets/images"),
  21. "@views": path.resolve(__dirname, "src/views"),
  22. "@store": path.resolve(__dirname, "src/store"),
  23. },
  24. },
  25. css: {
  26. // css预处理器
  27. preprocessorOptions: {
  28. less: {
  29. modifyVars: {
  30. // 全局less变量存储路径(配置less的全局变量)
  31. hack: `true; @import (reference) "${resolve('src/public/config.less')}";`,
  32. },
  33. javascriptEnabled: true,
  34. }
  35. }
  36. },
  37. build: {
  38. outDir: "dist",
  39. assetsDir: "assets", //指定静态资源存放路径
  40. sourcemap: false, //是否构建source map 文件
  41. // terserOptions: {
  42. // // 生产环境移除console
  43. // compress: {
  44. // drop_console: true,
  45. // drop_debugger: true,
  46. // },
  47. // },
  48. },
  49. server: {
  50. https: false, // 是否开启 https
  51. open: true, // 是否自动在浏览器打开
  52. port: port, // 端口号
  53. host: host,
  54. proxy: {
  55. "/api": {
  56. target: env.VITE_RES_URL, // 后台接口
  57. changeOrigin: true,
  58. secure: false, // 如果是https接口,需要配置这个参数
  59. ws: true, //websocket支持
  60. rewrite: (path) => path.replace(/^\/api/, ""),
  61. },
  62. },
  63. },
  64. }
  65. })

二. 打包后的结果如图所示,文件路径是./ 其实 去掉./是可以的,但是打包后是/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有关。欢迎各位大佬批评指正与补充!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/258708
推荐阅读
相关标签
  

闽ICP备14008679号