This module provides an echo middleware which automatically bundles assets using esbuild.
I am currently using to enable me to add typescript based stimulus controllers to a website while keeping the bundling process simple and integrated into the development lifecycle of the service so I can "watch" and rebuild everything.
Given the single NPM module provided by esbuild my node_modules
folder is also lean, which means less security issues.
The following example uses the middleware to provide bundle.js
via a script tag like <script src="/bundle.js"></script>
.
e := echo.New()
// register the asset bundler which will build then serve any asset files
e.Use(assets.BundlerWithConfig(assets.BundlerConfig{
EntryPoints: []string{"testassets/src/index.ts"},
Outfile: "bundle.js",
InlineSourcemap: true,
Define: map[string]string{
"process.env.NODE_ENV": `"production"`,
},
OnBuild: func(result api.BuildResult, timeTaken time.Duration) {
if len(result.Errors) > 0 {
log.Fatal().Fields(map[string]interface{}{
"errors": result.Errors,
}).Msg("failed to build assets")
}
},
OnRequest: func(req *http.Request, contentLength, code int, timeTaken time.Duration) {
log.Info().Str("path", req.URL.Path).Int("code", code).Str("timeTaken", timeTaken.String()).Msg("asset served")
},
}))
The next example builds files and stores them locally in an assets directory, this is typically used to bundle one ore more entry points prior to startup of the application.
// register the asset bundler which will build then serve any asset files
err := BuildWithConfig(BuildConfig{
EntryPoints: []api.EntryPoint{
{
InputPath: "testassets/src/index.ts",
OutputPath: "bundle",
},
},
InlineSourcemap: true,
Define: map[string]string{
"process.env.NODE_ENV": `"production"`,
},
OnBuild: func(result api.BuildResult, timeTaken time.Duration) {
if len(result.Errors) > 0 {
log.Fatal().Fields(map[string]interface{}{
"errors": result.Errors,
}).Msg("failed to build assets")
}
},
Outdir: "public/js",
})
if err != nil {
...
}
This code was authored by Mark Wolfe and licensed under the Apache 2.0 license.