Vite + Vue3 + Ts solves errors such as blank display of the index.html page generated by packaging, cross-domain reporting of resources, resource not found, 404-Page Not Found, etc.

Problem Description:

After using Vue3 + Ts for project development and building and packaging through Vite, when you directly open the index.html file in the dist directory after packaging and access in the local file system, the browser page is blank. , After opening the console, an error is reported, and the corresponding file cannot be found in this path.

Reason 1:

In the index.html file, the path of the referenced related resource file is incorrect, which causes the failure to load the file resource, because in most development processes, the default loading prefix for this static resource reference is "/".
insert image description here

Solution:

Open the vite.config.ts file in the project root directory. If there is no such file, create one manually (in fact, it is similar to vue.config.js in Vue2.x), and set the static resource base path "base" item to: Null character: " ", or: "./", or set the environment condition judgment according to the process.env.NODE_ENV variable, [also set the starting path of the loaded file to the current (and index.html) same level) path].

Note: If the project is in a subdirectory under the domain name, the value of the base item is: the directory name of the corresponding subdirectory! !
For example: the project is in the h5 directory under the domain name, then 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/, ''),
      }
    }
  },
})

Reason 2:

Since Vite is not designed for the traditional module system, the default output <script type=module>is ES Modules with type="module" to load and access files (js modules, css files, etc.),
for example:

  <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>

However, the above type="module" modular form of JS code is not allowed to access and run in the form of a file system in the browser! !
insert image description here

Solution:

This is a flaw, because most browsers do not support <script type="module" crossorigin="" src="./assets/xxx..js"></script>accessing js files directly in the browser with the type="module" method, that is ( ), this modular method needs to be accessed in the HTTP server environment. , so if you want to browse the project locally, you can also build an HTTP service environment.
You can quickly build a service environment with the help of some third-party tools. Common HTTP service tools are as follows:

Software class:

Browser application (plug-in) class:

Command line tool class:

If you have not installed any of the above tools, live-server or http-server are recommended here, because they are very convenient to install and use. You only need to execute the command in the command line tool.

/**
* 以下服务工具二选一即可!!
*/

// 全局安装live-server
npm install -g live-server

// 全局安装http-server
npm install -g http-server

// 启动HTTP服务:
	1、在打包生成后的dist目录下,打开命令行工具
	2、执行如下命令:
	
		live-server // 启动HTTP服务
		http-server // 启动HTTP服务

Extension:

Problem Description:

When you happily solve the above problems and start to launch the production environment, you may encounter the following problems after the launch is completed:

  1. The page can be accessed and browsed normally, but once you click to jump to another page route or refresh the page, a 404 - Page Not Found problem is reported! !

  2. The page can only be opened normally under the domain name. If /index.html is added after the domain name (such as https://www.xxx.com/index.html), the page cannot be found and cannot be displayed! !

Solution:

1. Change the routing mode

Change the routing mode in vue-router from createWebHistory() to 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. Modify the server configuration

Modify the configuration file corresponding to the production server:
1. Nginx server configuration

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

2. Apache server configuration

<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 server configuration

<?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>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324124839&siteId=291194637