解决vite打包的项目不能直接用浏览器运行HTML文件,Access to script at 'file:///D:/IdeaProjects/12.29/sales/dist/assets/index-DukojI2x.js' from origin 'null' has been blocked by CORS policy
遇到问题:
这是因为 现代浏览器的安全策略 限制了从 file:// 协议加载 ES 模块类型的资源。当你直接打开 HTML 文件时,浏览器将请求视为来自 null origin,而 CORS 策略不允许这种跨源请求。
解决方案参考:这篇文章:解决vite打包的项目不能直接用浏览器运行HTML文件
1.安装插件@vitejs/plugin-legacy
npm add @vitejs/plugin-legacy
2.配置vite.config.ts(没有就找vite.config.js)
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy'
export default defineConfig({
plugins: [
vue(),
legacy({
targets:["defaults","not IE 11"],
})
],
base: './',
})
vite默认根目录"/",file://…访问需要基于index.html的路径,将base修改为./解决文件路径不对问题。由于vite打包的项目涉及跨域,引入legacy可以解决file://…没有跨域的定义的问题。
3.配置路由
history: createWebHashHistory(),
修改路由为hash模式(小编就是因为没有选择hash模式浪费了不少时间),因为hash模式不会走服务器,而是在本地直接处理。
4.修改打包后的index.html文件
将index.html中所有的<script></script> 标签中的 type="module"、crossorigin、nomodule 删除,data-src 属性换成 src。
也可以写一个node脚本来处理
(1)安装 fs
npm add fs
(2)在项目根目录下新建html.js文件,写入下面代码
// 如果运行报错 Cannot use import statement outside a module 换成
//const fs = require("fs");
import fs from "fs";
const htmlPath = "./dist/index.html"; // 打包后的html文件路径
const htmlText = fs.readFileSync(htmlPath, 'utf8');
const htmlArr = htmlText.match(/.*\n/g) || [];
let result = "";
htmlArr.forEach(v => {
v = v
.replace(/script ?nomodule\s?/g, "script ")
.replace(/\s?crossorigin\s?/g, " ")
.replace(/data-src/g, 'src');
if (!v.includes(`script type="module"`)) {
result += v;
}
});
fs.writeFileSync(htmlPath, result, 'utf8');
console.log("处理完成");
直接点击运行此文件就好了。
浙公网安备 33010602011771号