vite2+vue3打包后浏览器打开跨域浏览器的错误

浏览器打开html.index :

 Access to script at 'file:///D:/hehai/viteObj/dist/assets/index.559fd86e.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

Vite 为没有传统模块系统设计,模块是其特性推荐。

或者,你可以在应用内部署一个自定义方案来使用这个嵌入页面(example-app://什么的),这样可以正常激活 ES Modules 特性,从规避问题开始。

解决方法一:

在VScode内安装Live Server插件

 配置 vite.config.ts

 打包好html.index后点击VSode 下的Go Live启动服务

 启动后默认5500端口 http://127.0.0.1:5500/dist/index.html

解决方法二:

@vitejs/plugin-legacy 43利用@vitejs/plugin-legacy 43生成没有模块的版本

vite.config.ts配置如下:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import legacy from '@vitejs/plugin-legacy';

// https://vitejs.dev/config/
export default defineConfig({
	base: './',
	plugins: [
		vue(),
		legacy({
			targets: ['ie>=11'],
			additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
		}),
	],
});

对打包后的index.html进行处理

  • 去除<script type=module>元素
  • 除去其他<script>nomodule属性
  • 移除<script id=vite-legacy-entry>元素的内容,并将data-src属性名改为src
  • 移除 <script id=vite-legacy-entry></script>内的代码
  • 将所有资源地址修改为相对地址(例如/assets/index-legacy.xxxx.js改为./assets/index-legacy.xxxx.js注意,还有 CSS 文件)

 

 直接浏览器打开index.html 问题解决

 注:此方法建议部署前做好充分测试

  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值