Plain is headed towards 1.0! Subscribe for development updates →

plain.esbuild

Build JavaScript files with esbuild.

gitignore

**/assets/**/*.esbuilt.*
 1import os
 2
 3import click
 4from watchfiles import Change, DefaultFilter, watch
 5
 6from plain.assets.finders import iter_asset_dirs, iter_assets
 7
 8from .core import esbuild, get_esbuilt_path
 9
10
11@click.group("esbuild")
12def cli():
13    pass
14
15
16@cli.command()
17@click.option("--minify", is_flag=True, default=True)
18def compile(minify):
19    returncode = 0
20    for asset in iter_assets():
21        if ".esbuild." in asset.absolute_path:
22            if not esbuild(
23                asset.absolute_path,
24                get_esbuilt_path(asset.absolute_path),
25                minify=minify,
26            ):
27                returncode = 1
28
29    if returncode:
30        exit(returncode)
31
32
33@cli.command()
34@click.pass_context
35def dev(ctx):
36    # Do an initial build of the assets
37    ctx.invoke(compile, minify=False)
38
39    asset_dirs = list(iter_asset_dirs())
40
41    class EsbuildFilter(DefaultFilter):
42        def __call__(self, change, path):
43            return super().__call__(change, path) and ".esbuild." in path
44
45    print("Watching for changes in .esbuild. asset files...")
46
47    for changes in watch(*asset_dirs, watch_filter=EsbuildFilter()):
48        for change, path in changes:
49            if change in [Change.added, Change.modified]:
50                esbuild(path, get_esbuilt_path(path))
51            elif change == Change.deleted:
52                dist_path = get_esbuilt_path(path)
53                if os.path.exists(dist_path):
54                    print(f"Deleting {os.path.relpath(dist_path)}")
55                    os.remove(dist_path)
56
57
58if __name__ == "__main__":
59    cli()