Things I want to do
This is a summary of the issues I encountered when running `npm run build` in a Vite environment, where the build process failed.
As a prerequisite, we are using a template that is compatible with our development environment. (We struggled with the configuration and other aspects without a template.)
(Updated regularly)
Build errors
await
When using `await`, the build failed with the following error:
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 do not allow the use of `await` at the top level (main thread).
As mentioned above, there is no problem as long as you do not use `await` at the top level. (Using `await` itself is not a problem.)
Solution
Stop using await.
If possible, you can avoid using `await` and instead implement the solution using `then` or `all`.
Run outside of the top level.
This can be addressed by implementing it to execute at a level other than the top-level, such as using `onclick`.
Changing the configuration file
By modifying the configuration file, you can prevent errors when using `await` at the top level.
The built code may not work in older browsers.
The file you need to edit is the configuration file that modifies defineConfig. Initially, it seems to be vite.config. In my environment (Phaser3 template), it was vite/config.prod.mjs.
Add the following settings. If you already have esbuild settings, add only ‘supported’.
export default defineConfig({
esbuild: {
supported: {
'top-level-await': true
},
}
})Runtime error
constructor.name
Code using `constructor.name` did not work after building.
The `.constructor.name` property of an arbitrary class was set to the class name, but the class name was changed during the build process, resulting in unexpected behavior. (In my case, it was an anonymous class, and `constructor.name` contained an empty string.)
Solution
Do not use constructor.name.
Even if it’s not an empty string, it’s best to avoid using class names because the name set may change due to version updates or other factors.
It’s simple and safe to add a named variable to the class. (If there’s another equivalent variable, use that instead.)
import() function
Importing from a bundled file fails. (This is expected since the path changes when bundled, but I didn’t notice because it worked in development mode.)
The following error will appear in the console:
Failed to fetch dynamically imported module:Solution
This can be resolved by importing it using a static import statement instead of a dynamic one.
Result
Without using a template, I struggled with folder structure and other issues, but by using a template suited to my development environment, I haven’t encountered any other problems so far.


コメント