赞
踩
在用Vue3 + Ts进行项目开发,通过Vite进行构建打包后,直接在本地以文件系统的方式,用浏览器直接打开打包生成后的dist目录下的index.html文件访问时,浏览器页面显示空白、打开控制台后有报错、该路径找不到对应的文件。
由于index.html文件中,引用的相关资源文件的路径不正确导致在加载文件资源时失败,因为在大多数开发过程中,这个静态资源引用加载的前缀 默认是 “/”。
在项目根目录中打开vite.config.ts文件,如果没有应该文件就手动创建一个(其实就和Vue2.x中的vue.config.js类似),将静态资源基础路径 “base” 项设为:空字符:" “,或者是:”./",再或者是根据process.env.NODE_ENV变量进行环境条件判断设置,【也是以将加载文件的起始路径,设置为从当前(和 index.html 同级)路径即可】。
注:如果项目是在域名下的某个子目录中,那么base项的值就是:对应子目录的目录名!!
例如:项目是在https://www.xxx.com域名下的 h5 目录中,那在打开的URL地址就是:https://www.xxx.com/h5,那么 base: ‘/h5’,
注:同时子目录 还需要在vue项目的router.ts路由配置createRouter()的 history 配置项中,也要加上对应的 h5目名才能访问哦!!
如:const router = createRouter({
history: createWebHashHistory(import.meta.env.BASE_URL as string), // 子目录 ‘/h5’
routes
});
import { defineConfig } from 'vite' import { resolve } from 'path' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [ vue(), ], // 静态资源基础路径 base: './' || '', // base: '/h5', // 子目录 base: process.env.NODE_ENV === 'production' ? './' : '/', publicDir: 'public', cacheDir: 'node_modules/.vite', 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: '//www.xxxx.com', changeOrigin: true, ws: true, secure: true, rewrite: (path) => path.replace(/^\/api/, ''), } } }, // 构建输出配置 build: { outDir: './dist', target: 'modules', assetsDir: 'assets', assetsInlineLimit: 360000, } })
由于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 'https://www.xxx.com/vue.js';
const app = createApp({...});
</script>
但是,以上这种type="module"模块化形式的JS代码,想要在浏览器中以文件服务的形式去访问运行不是被允许的!!
这个是硬伤,由于现在大部份浏览器还不支持直接在浏览器中,以type="module"方式,就是(<script type="module" crossorigin="" src="./assets/xxx..js"></script>
)访问js文件(不支持以文件服务方式打开),这种模块化的方式需要在HTTP服务器环境下才能访问,所以,如果想要在本地浏览项目也要搭建一个HTTP服务环境即可。
搭建本地服务环境可以借助一些第三方工具快速秒建,常见的本地HTTP服务器工具如下:
- 软件类:
- 浏览器扩展类:
- 命令行工具类(推荐):
如果你以上工具一个都没有安装的话,这里推荐 live-server 或 http-server,因为它们在安装 和 使用上都非常的方便,只需要在命令行工具中,执行命令就搞定了。
/** * 以下服务工具二选一即可!! */ // 全局安装live-server npm install -g live-server // 全局安装http-server npm install -g http-server // 启动HTTP服务: 1、在打包生成后的dist目录下,打开命令行工具 2、执行如下命令: live-server // 启动HTTP服务 或 http-server // 启动HTTP服务
命令行工具类安装成功后,在对应的打包生成后的目录下(一般是dist目录,或build目录 或自定义的项目录构建输出目录),打开命令行工具(Dos窗口)在里面输入 live-server 命令后,就会自动打开浏览器看到效果啦!具体如下图所示:
当你兴高采烈的把以上问题解决好以后,开始上线生产环境时,上线完成后,可能又会遇到以下问题:
页面可以正常访问浏览,一但点击跳转到别的页面路由 或者是 刷新页面时,报404 - Page Not Found问题!!
页面只能在域名下可以正常打开,如果在域名后面(如 https://www.xxx.com/index.html)加上/index.html,又找不到页面、无法显示了!!
将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 visited. component: () => 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;
修改对应生产服务器的配置文件:
1、Nginx服务器配置
# 在Nginx服务器的conf/nginx.conf配置文件中添加如下代码即可
location / {
try_files $uri $uri/ /index.html;
}
# 注:修改后nginx.conf配置文件后,一定要重启nginx服务,配置才能生效!
2、Apache 服务器配置
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /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>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。