Vite打成本地包可访问

处理打包之后不能直接访问的问题

安装

npm install @vitejs/plugin-legacy

配置 vite.config.js

import legacy from '@vitejs/plugin-legacy';
export default defineConfig({
...
  base: './',
  plugins: [vue(), legacy({ targets: ['defaults', 'not IE 11'] })],
})

在vite.config.js 同级目录下创建toFile.mjs (用于替换module等关键词,省的每次得手动删除)

import fs from 'fs'
console.time('转换耗时')
const distPath = './dist/index.html' //打包路径的index.html
let htmlText = fs.readFileSync(distPath, 'utf8')
let resultText = ''
let htmlArr = htmlText.match(/.*\n/g) || []
htmlArr.forEach((str) => {
  str = str.replace(/\s?nomodule\s?/g, ' ')
  str = str.replace(/\s?crossorigin\s?/g, ' ')
  str = str.replace(/data-src/g, 'src')
  if (!/type="module"/i.test(str)) resultText += str
})
fs.writeFileSync(distPath, resultText, 'utf8')
console.timeEnd('转换耗时')

package.json命令改为:

"build": "vite build && node toFile.mjs",

再次打包就可以了。

npm run build
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容