Skip to content

Commit

Permalink
Add support for env-variables
Browse files Browse the repository at this point in the history
  • Loading branch information
Richard87 committed Dec 23, 2021
1 parent 6b45f30 commit 542cb4f
Show file tree
Hide file tree
Showing 15 changed files with 104 additions and 21 deletions.
2 changes: 2 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
NODE_ENV=production
UNUSED_ENV=test
2 changes: 2 additions & 0 deletions .env.local
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
NODE_ENV=development
REACT_APP_TEST=Hello world!
3 changes: 2 additions & 1 deletion Caddyfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
admin off
}

http://localhost:8085 {
http://localhost:8080 {
file_server {
root example/public
}
esbuild ./example/src/index.js {
auto_reload
target /_build
sass
env
}
}
7 changes: 6 additions & 1 deletion README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ This plugins watches and builds the source files continiusly in-memory. It inclu
- [X] Live reload (v.0.1.0)
- [X] SASS (v. 0.2.2)
- [X] Manifest.json (v. 0.3.0) `/<target>/manifest.json`, defaults to `/_build/manifest.json`
- [ ] Env support (v.0.4.0)
- [X] Env support (v.0.4.0)
- [ ] Refactor to routes (v.0.5.0) (`route /_build {esbuild assets/index.js auto_reload sass}`)
- [ ] Custom loader configuration?

Expand All @@ -30,6 +30,11 @@ localhost:8080 {
}
```

## Documentation:
- Env support: esbuild will include all environment variables starting with `REACT_APP_` and bundle it with your application,
*including unused items*. It will scan any `.env`, `.env.<NODE_ENV>`, `.env.<NODE_ENV>.local`, and the runtime environment for relevant variables.
It will however not watch them changes or auto-reload them.

## Devlopment:

To run: `xcaddy run -watch`
Expand Down
2 changes: 2 additions & 0 deletions caddyfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ func parseCaddyfileEsbuild(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler,
return nil, h.Err("sass requires caddy to be compiled with CGO and libsass available")
}
esbuild.Sass = true
case "env":
esbuild.Env = true
case "target":
if !h.NextArg() {
return nil, h.ArgErr()
Expand Down
21 changes: 17 additions & 4 deletions esbuild.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,17 @@ import (
"time"
)

type Process struct {
Env map[string]string `json:"env"`
}

func (m *Esbuild) initEsbuild() {
var inject []string
define := make(map[string]string)
var plugins []api.Plugin

plugins = append(plugins, m.createTimingPlugin())

if m.AutoReload && isJsFile(m.Source) {
name, err := m.createAutoloadShimFile()
if err != nil {
Expand All @@ -32,12 +39,17 @@ func (m *Esbuild) initEsbuild() {
}
}

if m.Env {
define["process"] = m.handleEnv()
}

start := time.Now()
result := api.Build(api.BuildOptions{
EntryPoints: []string{m.Source},
Sourcemap: api.SourceMapLinked,
Outdir: m.Target,
PublicPath: m.Target,
Define: define,
Metafile: true,
Write: false,
Bundle: true,
Expand All @@ -53,14 +65,15 @@ func (m *Esbuild) initEsbuild() {
Watch: &api.WatchMode{
OnRebuild: func(result api.BuildResult) {
m.logger.Debug("Rebuild completed!")
m.onBuild(result, 0)
m.onBuild(result, m.lastDuration)
},
},
})
duration := time.Now().Sub(start)
m.onBuild(result, duration)
m.onBuild(result, &duration)
}
func (m *Esbuild) onBuild(result api.BuildResult, duration time.Duration) {

func (m *Esbuild) onBuild(result api.BuildResult, duration *time.Duration) {

for _, err := range result.Errors {
m.logger.Error(err.Text)
Expand All @@ -86,7 +99,7 @@ func (m *Esbuild) Rebuild() {
start := time.Now()
result := m.esbuild.Rebuild()
duration := time.Now().Sub(start)
m.onBuild(result, duration)
m.onBuild(result, &duration)
}
}

Expand Down
1 change: 1 addition & 0 deletions example/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ function App() {
>
Learn React with EsBuild
</a>
{process.env.REACT_APP_TEST}
<div className={"alert alert-primary"}><h1>Hello world!</h1></div>
</header>
</div>
Expand Down
2 changes: 1 addition & 1 deletion example/sub.scss
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
$test: #054150;
$primary: green;
$primary: blue;

body {
color: white;
Expand Down
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ go 1.17
require (
github.com/caddyserver/caddy/v2 v2.4.6
github.com/evanw/esbuild v0.14.6
github.com/fsnotify/fsnotify v1.4.9
github.com/joho/godotenv v1.3.0
github.com/wellington/go-libsass v0.9.3-0.20201023163432-90bbc073a203
go.uber.org/zap v1.19.0
)
Expand All @@ -27,7 +29,6 @@ require (
github.com/dgraph-io/ristretto v0.0.4-0.20200906165740-41ebdbffecfd // indirect
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/dustin/go-humanize v1.0.1-0.20200219035652-afde56e7acac // indirect
github.com/fsnotify/fsnotify v1.4.9 // indirect
github.com/go-kit/kit v0.10.0 // indirect
github.com/go-logfmt/logfmt v0.5.0 // indirect
github.com/go-sql-driver/mysql v1.6.0 // indirect
Expand Down Expand Up @@ -79,6 +80,7 @@ require (
github.com/urfave/cli v1.22.5 // indirect
go.etcd.io/bbolt v1.3.6 // indirect
go.mozilla.org/pkcs7 v0.0.0-20210826202110-33d05740a352 // indirect
go.step.sm/cli-utils v0.6.0 // indirect
go.step.sm/crypto v0.11.0 // indirect
go.step.sm/linkedca v0.5.0 // indirect
go.uber.org/atomic v1.7.0 // indirect
Expand Down
10 changes: 1 addition & 9 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,7 @@ github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeY
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc=
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8=
Expand Down Expand Up @@ -900,14 +901,6 @@ github.com/urfave/cli v1.22.5 h1:lNq9sAHXK2qfdI8W+GRItjCEkI+2oR4d+MEHy1CKXoU=
github.com/urfave/cli v1.22.5/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
github.com/viant/assertly v0.4.8/go.mod h1:aGifi++jvCrUaklKEKT0BU95igDNaqkvz+49uaYMPRU=
github.com/viant/toolbox v0.24.0/go.mod h1:OxMCG57V0PXuIP2HNQrtJf2CjqdmbrOx5EkMILuUhzM=
github.com/wellington/go-libsass v0.9.2 h1:6Ims04UDdBs6/CGSVK5JC8FNikR5ssrsMMKE/uaO5Q8=
github.com/wellington/go-libsass v0.9.2/go.mod h1:mxgxgam0N0E+NAUMHLcu20Ccfc3mVpDkyrLDayqfiTs=
github.com/wellington/go-libsass v0.9.3-0.20180616180904-a8861c8860b0 h1:nkDd0sxRh9j0NmAwpO1hT5K4NDqks1bLySZpriWaCZ8=
github.com/wellington/go-libsass v0.9.3-0.20180616180904-a8861c8860b0/go.mod h1:mxgxgam0N0E+NAUMHLcu20Ccfc3mVpDkyrLDayqfiTs=
github.com/wellington/go-libsass v0.9.3-0.20190211161420-e17b670b82b3 h1:QyotHK+ND+lwWJl5RSaIEavMwxz/CymfkueMp9juqb4=
github.com/wellington/go-libsass v0.9.3-0.20190211161420-e17b670b82b3/go.mod h1:mxgxgam0N0E+NAUMHLcu20Ccfc3mVpDkyrLDayqfiTs=
github.com/wellington/go-libsass v0.9.3-0.20190212124126-f870eaa15594 h1:Cm9ttMJaq5IYZW9RzserHlaibyWSwDJGt5upuKABoKs=
github.com/wellington/go-libsass v0.9.3-0.20190212124126-f870eaa15594/go.mod h1:mxgxgam0N0E+NAUMHLcu20Ccfc3mVpDkyrLDayqfiTs=
github.com/wellington/go-libsass v0.9.3-0.20201023163432-90bbc073a203 h1:m9SsgZCIXLdSvbm3vtIkFpdyk1jsu76CinQJZakCOZ4=
github.com/wellington/go-libsass v0.9.3-0.20201023163432-90bbc073a203/go.mod h1:mxgxgam0N0E+NAUMHLcu20Ccfc3mVpDkyrLDayqfiTs=
github.com/weppos/publicsuffix-go v0.4.0/go.mod h1:z3LCPQ38eedDQSwmsSRW4Y7t2L8Ln16JPQ02lHAdn5k=
Expand Down Expand Up @@ -1137,7 +1130,6 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210913180222-943fd674d43e h1:+b/22bPvDYt4NPDcy4xAGCmON713ONAWFeY3Z7I3tR8=
golang.org/x/net v0.0.0-20210913180222-943fd674d43e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211216030914-fe4d6282115f h1:hEYJvxw1lSnWIl8X9ofsYMklzaDs90JI2az5YMd4fPM=
golang.org/x/net v0.0.0-20211216030914-fe4d6282115f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
Expand Down
36 changes: 36 additions & 0 deletions handle_env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package caddy_esbuild_plugin

import (
"encoding/json"
"github.com/joho/godotenv"
"go.uber.org/zap"
"os"
"strings"
)

func (m *Esbuild) handleEnv() string {
process := Process{Env: map[string]string{}}
currentEnv := os.Getenv("NODE_ENV")
if currentEnv == "" {
currentEnv = "development"
}

_ = godotenv.Load(".env." + currentEnv + ".local")
_ = godotenv.Load(".env.local")
_ = godotenv.Load(".env." + currentEnv)
err := godotenv.Load()

process.Env["NODE_ENV"] = os.Getenv("NODE_ENV")
if err != nil {
m.logger.Error("Failed to load env", zap.Error(err))
} else {
for _, pair := range os.Environ() {
item := strings.SplitN(pair, "=", 2)
if strings.HasPrefix(item[0], "REACT_APP_") {
process.Env[item[0]] = item[1]
}
}
}
processJson, _ := json.Marshal(process)
return string(processJson)
}
File renamed without changes.
File renamed without changes.
11 changes: 7 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,21 @@ import (
"go.uber.org/zap"
"net/http"
"strings"
"time"
)

type Esbuild struct {
Source string `json:"source,omitempty"`
Target string `json:"target,omitempty"`
AutoReload bool `json:"auto_reload,omitempty"`
Sass bool `json:"sass,omitempty"`
Env bool `json:"env,omitempty"`

logger *zap.Logger
esbuild *api.BuildResult
hashes map[string]string
globalQuit chan struct{}
logger *zap.Logger
esbuild *api.BuildResult
hashes map[string]string
globalQuit chan struct{}
lastDuration *time.Duration
}

func (m *Esbuild) Cleanup() error {
Expand Down
24 changes: 24 additions & 0 deletions plugin_timing.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package caddy_esbuild_plugin

import (
"github.com/evanw/esbuild/pkg/api"
"time"
)

func (m *Esbuild) createTimingPlugin() api.Plugin {
return api.Plugin{
Name: "timingPlugin",
Setup: func(build api.PluginBuild) {
var start time.Time

build.OnStart(func() (api.OnStartResult, error) {
start = time.Now()
return api.OnStartResult{}, nil
})
build.OnEnd(func(result *api.BuildResult) {
duration := time.Now().Sub(start)
m.lastDuration = &duration
})
},
}
}

0 comments on commit 542cb4f

Please sign in to comment.