vben admin打包报ERROR: Top-level await is not available in the configured target environment

使用Vue-Vben-Admin框架快速开发后台,build打包报错导致打包被终止,错误信息为:

ERROR  [vite:esbuild-transpile] Transform failed with 1 error:                                                                                                                                                                                                      10:04:01  
assets/index.d37e9792.js:17:13: ERROR: Top-level await is not available in the configured target environment ("chrome90", "edge90", "es2015", "firefox90", "safari15")

Top-level await is not available in the configured target environment ("chrome90", "edge90", "es2015", "firefox90", "safari15")
15 |
16 | const labelMinWidth = 80;
17 | const data = await getOrganizationAllTree({ hasRoot: false });
| ^
18 | const detailSchema = [
19 | {

错误原因:

「ECMAScript」提案 Top-level await 由 Myles Borins 提出,它可以让你在模块的最高层中使用 await 操作符。在这之前,你只能通过在 async 函数或 async generators 中使用 await 操作符。Top-level await 是个新特性,打包不支持此特性。

知道了错误引起的原因,那么我们就可以根据该原因来解决问题。步骤如下:

一、安装vite-plugin-top-level-await插件

npm install vite-plugin-top-level-await -D

cnpm install vite-plugin-top-level-await -D

注:cnpm为镜像安装

二、在vite.config.js中配置该插件

import topLevelAwait from 'vite-plugin-top-level-await'

export default defineConfig({
plugins: [
topLevelAwait({
// The export name of top-level await promise for each chunk module
promiseExportName: '__tla',
// The function to generate import names of top-level await promise in each chunk module
promiseImportName: i => `__tla_${i}`
})
]
});

注:若你的配置中是如下方式,则继续向下看。

plugins: createVitePlugins(viteEnv, isBuild)

找到build/vite/plugin/index.ts文件,同理引入该文件

import topLevelAwait from 'vite-plugin-top-level-await';

然后在vitePlugins中配置

topLevelAwait({  
    // The export name of top-level await promise for each chunk module
promiseExportName: '__tla',
// The function to generate import names of top-level await promise in each chunk module
promiseImportName: i => `__tla_${i}`
})

如图:


然后,重新打包即可。


六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!