문제 설명:
Vite를 통해 프로젝트 개발 및 빌드 및 패키징에 Vue3 + Ts를 사용한 후 로컬 파일 시스템에서 패키징 및 액세스 후 dist 디렉토리의 index.html 파일을 직접 열면 브라우저 페이지가 비어 있습니다. , 콘솔을 연 후, 오류가 보고되고 해당 파일을 이 경로에서 찾을 수 없습니다.
이유 1:
index.html 파일에서 참조된 관련 리소스 파일의 경로가 올바르지 않아 대부분의 개발 프로세스에서 이 정적 리소스 참조에 대한 기본 로딩 접두사가 "/"이기 때문에 파일 리소스 로드에 실패합니다.
해결책:
프로젝트 루트 디렉터리에 vite.config.ts 파일을 열고 해당 파일이 없으면 수동으로 생성(사실 Vue2.x의 vue.config.js와 유사)하고 정적 리소스 기본 경로를 설정합니다. "base" 항목을 Null 문자: " " 또는: "./"로 설정하거나 process.env.NODE_ENV 변수에 따라 환경 조건 판단을 설정하고 [로드된 파일의 시작 경로를 현재(및 index.html) 같은 수준) 경로].
참고: 프로젝트가 도메인 이름 아래의 하위 디렉터리에 있는 경우 기본 항목의 값은 다음과 같습니다. 해당 하위 디렉터리의 디렉터리 이름! !
예: 프로젝트는 도메인 이름 아래의 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: '//www.xxxx.com',
changeOrigin: true,
ws: true,
secure: true,
rewrite: (path) => path.replace(/^\/api/, ''),
}
}
},
})
이유 2:
Vite는 기존 모듈 시스템용으로 설계되지 않았기 때문에 기본 출력 <script type=module>
은 파일(js 모듈, CSS 파일 등)을 로드하고 액세스하기 위한 type="module"인 ES 모듈입니다.
예를 들면 다음과 같습니다.
<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 코드는 브라우저에서 파일 시스템 형태로 접근하여 실행할 수 없습니다! !
해결책:
이는 대부분 <script type="module" crossorigin="" src="./assets/xxx..js"></script>
의 브라우저가 type="module" 메소드, 즉 ( )를 사용하여 브라우저에서 직접 js 파일에 액세스하는 것을 지원하지 않기 때문에 이 모듈식 메소드는 HTTP 서버 환경에서 액세스해야 하므로 결함입니다. 프로젝트를 로컬로 탐색하기 위해 HTTP 서비스 환경을 구축할 수도 있습니다.
일부 타사 도구를 사용하여 서비스 환경을 빠르게 구축할 수 있습니다. 일반적인 HTTP 서비스 도구는 다음과 같습니다.
소프트웨어 클래스:
- WampServer 다운로드 주소: https://www.wampserver.com
- XAMPP 다운로드 주소: https://www.apachefriends.org/download.html
- PhpStudy 다운로드 주소: https://www.xp.cn/
브라우저 애플리케이션(플러그인) 클래스:
- WebServerforChrome 다운로드 주소: https://www.gugeapps.net/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb
명령줄 도구 클래스:
- live-server // 다운로드 주소: https://www.npmjs.com/package/live-server
- http-server // 다운로드 주소: https://www.npmjs.com/package/http-server
위의 도구를 설치하지 않은 경우 설치 및 사용이 매우 편리한 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服务
확대:
문제 설명:
위의 문제를 만족스럽게 해결하고 프로덕션 환경을 시작하면 시작이 완료된 후 다음과 같은 문제가 발생할 수 있습니다.
-
페이지는 정상적으로 액세스하고 탐색할 수 있지만 클릭하여 다른 페이지 경로로 이동하거나 페이지를 새로 고치면 404 - 페이지를 찾을 수 없음 문제가 보고됩니다! !
-
페이지는 도메인 이름으로만 정상적으로 열릴 수 있으며, 도메인 이름 뒤에 /index.html을 추가하면(예: https://www.xxx.com/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 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;
2. 서버 구성 수정
프로덕션 서버에 해당하는 구성 파일 수정:
1. Nginx 서버 구성
# 在Nginx服务器的conf/nginx.conf配置文件中添加如下代码即可
location / {
try_files $uri $uri/ /index.html;
}
# 注:修改后nginx.conf配置文件后,一定要重启nginx服务,配置才能生效!
2. 아파치 서버 설정
<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>