什么?vite+vue3 打包后不能直接访问index.html

698 阅读1分钟

一般我们用vite + vue3 打包的文件,直接点击打开index.html文件,页面会白屏,打开调试工具后发现跨域的报错。但是我们使用类似于nginx或者其他的服务器打开,可以正常打开。因为跨源请求仅支持协议方案:http、data、chrome、chrome-extension、chrom-untrusted、https,不支持file协议。

下面将解决 vite 打包后在本地浏览器直接打开index.html文件不能访问问题,步骤如下:

一、安装兼容插件 @vitejs/plugin-legacy

npm安装

npm install --save-dev @vitejs/plugin-legacy

yarn安装

yarn add @vitejs/plugin-legacy --dev

二、在vite.config.js 中进行配置

添加如下内容
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy';  
// https://vitejs.dev/config/
export default defineConfig({
  base: "./",  // 1.需要加上此处
  plugins: [
    vue(),
    legacy({  // 2.需要加上此处
      targets:["defaults","not IE 11"],
      additionalLegacyPolyfills: ["regenerator-runtime/runtime"]
    })],
})

三、修改index.html文件

在根目录下的index.html文件中的尾部添加如下script:
<script>
  (function (win) {
    let scripts = document.getElementsByTagName("script");
    for (let i = 0; i < scripts.length; i++) {
      let script = scripts[i];
      let url = script.getAttribute("src");
      let type = script.getAttribute("type");
      let scriptText = script.innerHTML;
      if (url || type === "module") {
        let tag = document.createElement("script");
        tag.setAttribute("url", url);
        tag.innerHTML = scriptText;
        script.remove();
        document.getElementsByTagName("head")[0].appendChild(tag);
      }
    }
  })(window);
</script>

四、直接打开打包文件dist的index.html文件

在浏览器就可以看到index.html正常显示了

以上四步将解决打包文件dist的index.html文件不能直接访问的问题。