vue build index直接打开静态页面

发布时间 2023-09-27 21:11:57作者: Veyron16

vite + vue3 打包的文件,如果使用类似于nginx或者其他的服务器打开,可以正常打开,但如果直接点击打开index.html文件,页面会白屏,打开调试工具后发现如下跨域的报错。

这是因为打包后并不支持file引用协议。这就给混合式开发等时候带来困扰,因为在这种场景下,是有需要直接打开index.html文件的需求的。
在经历一段时间的困扰后,还是找到了解决方案。

1.安装兼容插件 @vitejs/plugin-legacy

npm i  @vitejs/plugin-legacy

在vite.config.ts 中进行配置(可忽略)

// 引入@vitejs/plugin-legacy
import legacy from '@vitejs/plugin-legacy';
// 在plugins中添加
legacy({
  targets: ['defaults', 'not IE 11']
}),

2.手动修改打包完的index.html文件(不建议使用,可直接略过使用第三步)

先执行 npm run build 命令进行打包,打包完成后打开 dist/index.html。
将index.html中所有的 标签中的 type="module"、crossorigin、nomodule 删除。

举例
修改前
……
<script type="module" crossorigin src="./assets/index.5617d2f4.js"></script>
<script nomodule crossorigin id="vite-legacy-polyfill" src="./assets/polyfills-legacy.7fa4d18d.js"></script>
……
修改后
 <script src="./assets/index.5617d2f4.js"></script>
<script id="vite-legacy-polyfill" src="./assets/polyfills-legacy.7fa4d18d.js"></script>

3.自动修改打包完的index.html文件(建议使用)

在项目的根目录下的index.html文件中的尾部添加新的来处理,一定要添加在尾部。

<script>
  (function (win) {
    // 获取页面所有的 <script > 标签对象
    let scripts = document.getElementsByTagName('script')
    // 遍历标签
    for(let i = 0; i < scripts.length; i++) {
      // 提取单个<script > 标签对象
      let script = scripts[i]
      // 获取标签中的 src
      let url = script.getAttribute("src")
      // 获取标签中的 type
      let type = script.getAttribute("type")
      // 获取标签中的js代码
      let scriptText = script.innerHTML
      // 如果有引用地址或者 type 属性 为 "module" 则代表该标签需要更改
      if (url || type === "module") {
        // 创建一个新的标签对象
        let tag=document.createElement('script');
        // 设置src的引入
        tag.setAttribute('url',url);
        // 设置js代码
        tag.innerHTML = scriptText
        // 删除原先的标签
        script.remove()
        // 将标签添加到代码中
        document.getElementsByTagName('head')[0].appendChild(tag)
      }
    }
  })(window)
</script>

如上,就可以正常双击打开打包完的index.html运行项目了。