vue3+vist 打包空白
一、问题
在使用vue3.2和vite2.0+开发一个移动端H5,测试时发现很多低版本的安卓手机浏览器出现白屏的现象,而ios机型基本上是好的,原因是很多低版本浏览器并不支持原生ESM导入的方式,下面给出解决方案:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec.
二、兼容原生ESM的浏览器
在使用vue3.2和vite2.0+开发一个移动端H5,测试时发现很多低版本的安卓手机浏览器出现白屏的现象,而ios机型基本上是好的,原因是很多低版本浏览器并不支持原生ESM导入的方式,下面给出解决方案:默认情况下,Vite 的目标浏览器是指能够 支持原生 ESM script 标签 和 支持原生 ESM 动态导入 的。作为参考,Vite 使用这个 browserslist 作为查询标准:
Chrome >=87
Firefox >=78
Safari >=13
Edge >=88
三、解决方案
步骤一: vite.config.ts里 build.target 配置项 指定构建目标为 es2015 步骤二: 通过插件 @vitejs/plugin-legacy 来自动生成传统浏览器的 chunk 及与其相对应 ES 语言特性方面的 polyfill。兼容版的 chunk 只会在不支持原生 ESM 的浏览器中进行按需加载。
1. 安装@vitejs/plugin-legacy
yarn add @vitejs/plugin-legacy
2. 配置 vite.config.ts
import { fileURLToPath, URL } from 'node:url'
import legacy from '@vitejs/plugin-legacy'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
base: './',
plugins: [
vue(),
legacy({
targets: [
'> 1%, last 1 version, ie >= 11',
'safari >= 10',
'Android > 39',
'Chrome >= 60',
'Safari >= 10.1',
'iOS >= 10.3',
'Firefox >= 54',
'Edge >= 15'
],
additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
polyfills: ['es.promise.finally', 'es/map', 'es/set'],
modernPolyfills: ['es.promise.finally']
})
],
build: {
target: 'es2015'
},
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})
如果编译报错:
x Build failed in 2.92s
error during build:
Error: [vite:terser] terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.
at loadTerserPath (file:///D:/project/_SZL/vue-project/node_modules/vite/dist/node/chunks/dep-jvB8WLp9.js:15226:19)
at Object.renderChunk (file:///D:/project/_SZL/vue-project/node_modules/vite/dist/node/chunks/dep-jvB8WLp9.js:15265:32)
at file:///D:/project/_SZL/vue-project/node_modules/rollup/dist/es/shared/node-entry.js:19563:40
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
error Command failed with exit code 1.
解决方案:
yarn add terser --legacy--peer-deps
参考:
https://www.jb51.net/javascript/290338iub.htm
https://zhuanlan.zhihu.com/p/595407605