The purpose
Here’s a summary of issues encountered when building a Vite project using npm run build
.
The build did not work correctly. This is based on using a template for the development environment (using no template proved too challenging in terms of configuration).
(This document will be updated as needed).
Build error
await
Building failed with the following error when using await.
ERROR: Top-level await is not available in the configured target environment ("chrome87", "edge88", "es2020", "firefox78", "safari14" + 2 overrides)
This appears to be a compatibility issue causing an error because older browsers don’t allow the use of await
at the top level (main thread).
As shown above, avoiding top-level await
resolves the problem. (Using await
itself is not the issue.)
Solution
Stop awaiting
If possible, avoid using await
and instead implement the solution using then
or Promise.all
.
Run outside the top level
This can be addressed by implementing it to run outside the top level, such as using ‘onclick’ elsewhere.
Change setting
Modifying the configuration file will prevent errors from occurring when using await
at the top level.
The built code may not work on older browsers.
The file to be edited is the configuration file that modifies defineConfig
. Initially, it appears to be vite.config
.
In my environment (a Phaser 3 template), it was vite/config.prod.mjs
. The following settings will be added. If esbuild settings already exist, only add supported
.
export default defineConfig({
esbuild: {
supported: {
'top-level-await': true
},
}
})
Runtime error
constructor.name
The code using constructor.name
failed after building.
While anyClass.constructor.name
usually reflects the class name, the class name changed during the build process, causing unexpected behavior. In my case, it resulted in an anonymous class, leaving constructor.name
empty.
Solution
Avoid using constructor.name
.
Even if it’s not empty, the name might change due to version upgrades or other updates, so it’s best to avoid using the class name.
Adding a dedicated named variable to the class is the simplest and safest approach. (If a similar variable already exists, use that instead.)
import() function
Importing from files included in the bundle fails (this is expected because the paths change after bundling; I didn’t notice this during development).
The console displays the following error:
Failed to fetch dynamically imported module:
Solution
This can be solved by importing using a static import statement instead of a dynamic one.
Result
I struggled with the folder structure and other aspects without using a template, but by using a template suited to my development environment, so far I’ve only encountered the problems mentioned above.
comment