1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Vite + Vue3 + Ts 解决打包生成的index.html页面显示空白 报资源跨域 找不到资

Vite + Vue3 + Ts 解决打包生成的index.html页面显示空白 报资源跨域 找不到资

时间:2022-10-21 09:15:13

相关推荐

Vite + Vue3 + Ts 解决打包生成的index.html页面显示空白 报资源跨域 找不到资

问题描述:

在用Vue3 + Ts进行项目开发,通过Vite进行构建打包后,直接在本地以文件系统的方式,用浏览器直接打开打包生成后的dist目录下的index.html文件访问时,浏览器页面显示空白、打开控制台后有报错、该路径找不到对应的文件。

原因1:

由于index.html文件中,引用的相关资源文件的路径不正确导致在加载文件资源时失败,因为在大多数开发过程中,这个静态资源引用加载的前缀 默认是 “/”。

解决方法:

在项目根目录中打开vite.config.ts文件,如果没有应该文件就手动创建一个(其实就和Vue2.x中的vue.config.js类似),将静态资源基础路径 “base” 项设为:空字符:" “,或者是:”./",再或者是根据process.env.NODE_ENV变量进行环境条件判断设置,【也是以将加载文件的起始路径,设置为从当前(和 index.html 同级)路径即可】。

注:如果项目是在域名下的某个子目录中,那么base项的值就是:对应子目录的目录名!!

例如:项目是在域名下的 h5 目录中,那么 base: ‘/h5/’,

import { defineConfig } from 'vite'import { resolve } from 'path'import vue from '@vitejs/plugin-vue'export default defineConfig({plugins: [vue(),],// 静态资源基础路径 base: './' || '',base: process.env.NODE_ENV === 'production' ? './' : '/',alias: {// 配置目录别名'@': resolve(__dirname, 'src'),'views': resolve(__dirname, 'src/views'),'utils': resolve(__dirname, 'src/utils'),},css: {// css预处理器preprocessorOptions: {less: {modifyVars: {// 全局less变量存储路径(配置less的全局变量)hack: `true; @import (reference) "${resolve('src/public/config.less')}";`,},javascriptEnabled: true,}}},// 开发服务器配置server: {host: true,open: true,port: 3000,proxy: {'/api': {target: '//',changeOrigin: true,ws: true,secure: true,rewrite: (path) => path.replace(/^/api/, ''),}}},})

原因2:

由于Vite 没有为传统模块系统设计, 默认输出<script type=module>就是 ES Modules 以type="module"模块化的方式,来加载和访问文件(js模块,css文件等),

例如:

<script type="module">// 在type="module"模式下,可以在Web开发时直接以ES6+的模块化的方式来导入js资源模块。// 引入本地js资源模块方式import { createApp } from './script/vue.js';// 引入网络js资源模块方式 【注:Node.js中的引入是不支持这种网络请求哦!!】import { createApp } from '/vue.js';const app = createApp({...});</script>

但是,以上这种type="module"模块化形式的JS代码,想要在浏览器中以文件系统的形式去访问运行不是被允许的!!

解决方法:

这个是硬伤,由于现在大部份浏览器还不支持直接在浏览器中,以type="module"方式,就是(<script type="module" crossorigin="" src="./assets/xxx..js"></script>)访问js文件,这种模块化的方式需要在HTTP服务器环境下才能访问,所以,如果想要在本地浏览项目也要搭建一个HTTP服务环境即可。

搭建服务环境可以借助一些第三方工具快速秒建,常见的HTTP服务工具如下:

软件类:

WampServer 下载地址:XAMPP 下载地址:/download.htmlPhpStudy 下载地址:/

浏览器应用(插件)类:

WebServerforChrome 下载地址:/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb

命令行工具类:

live-server // 下载地址:/package/live-serverhttp-server // 下载地址:/package/http-server

如果你以上工具一个都没有安装的话,这里推荐live-server 或 http-server,因为它们在安装 和 使用上都非常的方便,只需要在命令行工具中,执行命令就搞定了。

/*** 以下服务工具二选一即可!!*/// 全局安装live-servernpm install -g live-server// 全局安装http-servernpm install -g http-server// 启动HTTP服务:1、在打包生成后的dist目录下,打开命令行工具2、执行如下命令:live-server // 启动HTTP服务或http-server // 启动HTTP服务

扩展:

问题描述:

当你兴高采烈的把以上问题解决好以后,开始上线生产环境时,上线完成后,可能又会遇到以下问题:

页面可以正常访问浏览,一但点击跳转到别的页面路由 或者是 刷新页面时,报404 - Page Not Found问题!!

页面只能在域名下可以正常打开,如果在域名后面(如 /index.html)加上/index.html,又找不到页面、无法显示了!!

解决方法:

1、改变路由模式

将vue-router中的路由模式从createWebHistory() 改为 createWebHashHistory()即可。

import { createRouter, createWebHistory, createWebHashHistory, RouteRecordRaw } from 'vue-router'import Home from '../views/Home.vue'const routes: Array<RouteRecordRaw> = [{path: '/',name: 'Home',component: Home,},{path: '/about',name: 'About',// route level code-splitting// this generates a separate chunk (about.[hash].js) for this route// which is lazy-loaded when the route is ponent: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),},];const router = createRouter({// history: createWebHistory(import.meta.env.VITE_BASE_PATH as string),history: createWebHashHistory(import.meta.env.VITE_BASE_PATH as string), // 改为这种HASH路由模式routes,});export default router;

2、修改服务器配置

修改对应生产服务器的配置文件:

1、Nginx服务器配置

# 在Nginx服务器的conf/nginx.conf配置文件中添加如下代码即可location / {try_files $uri $uri/ /index.html;}# 注:修改后nginx.conf配置文件后,一定要重启nginx服务,配置才能生效!

2、Apache 服务器配置

<IfModule mod_rewrite.c>RewriteEngine OnRewriteBase /RewriteRule ^index.html$ - [L]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule . /index.html [L]</IfModule>

3、IIS 服务器配置

<?xml version="1.0" encoding="UTF-8"?><configuration><system.webServer><rewrite><rules><rule name="AngularJS" stopProcessing="true"><match url=".*" /><conditions logicalGrouping="MatchAll"><add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /><add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /></conditions>//将url中的参数设为 "/" 或者 "/index.html" <action type="Rewrite" url="/" /></rule></rules></rewrite></system.webServer></configuration>

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。