本地运行vue3打包后的index.html文件

706 阅读1分钟

参考文章: 解决vite打包的项目不能直接用浏览器运行HTML文件-CSDN博客

遇到一个开发本地web工具的需求,第一次做到处摸索,最终使用参考文章中的方式解决问题。

1、安装插件@vitejs/plugin-legacy

npm install @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({
  base: './',
  plugins: [
    vue(),
    legacy({
      targets: ["defaults", "not IE 11"],
    })
  ],
})

3.配置路由 路由文件router中使用createWebHashHistory创建route

import {
    createRouter,
    createWebHashHistory,
} from 'vue-router'

const routes = [
    {   // 默认页面
        path: '/',
        redirect: ''
    },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

export default router

截止第三步,我已经可以打开build后的index.html文件。如果还不能打开就继续往下走

4.修改打包后的index.html文件

将index.html中所有的 标签中的 type="module"、crossorigin、nomodule 删除,data-src 属性换成 src。

也可以写一个node脚本来处理

(1)安装 fs

pnpm add fs

(2)在项目根目录下新建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("处理完成");

(3)在 package.json 里面配置脚本

  "scripts": {
    //...//
    "html": "node HandleHTML.js"  //"执行名称": "node 文件名"
  },

(4)终端执行代码

npm html

有效的话多去原文章给作者点赞留言哦~ 原地址:解决vite打包的项目不能直接用浏览器运行HTML文件-CSDN博客