forked from Alwatr/fract
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathesbuild.mjs
executable file
·176 lines (140 loc) · 4.97 KB
/
esbuild.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/env node
/* eslint-disable no-undef */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import {execSync} from 'child_process';
import {promises as fs, existsSync} from 'node:fs';
import {createLogger} from '@alwatr/logger';
import postCssPlugin from '@deanc/esbuild-plugin-postcss';
import postcssPresetEnv from 'postcss-preset-env';
import * as esbuild from 'esbuild';
import postcssImport from 'postcss-import';
import postcssTailwind from 'tailwindcss';
import postcssNesting from 'tailwindcss/nesting/index.js';
import {generateSW} from 'workbox-build';
import packageJson from './package.json' assert {type: 'json'};
const logger = createLogger('alwatr-pwa-build');
const banner = '/* ..:: Alwatr PWA ::.. */\n';
const srcDir = 'src';
const resDir = 'res';
const outDir = 'dist';
const srcFilename = 'main';
const cleanMode = process.argv.includes('--clean');
const watchMode = process.argv.includes('--watch');
const debugMode = process.argv.includes('--debug');
const prettyMode = process.argv.includes('--pretty');
const gitShortSha = execSync('git rev-parse --short HEAD').toString().trim();
logger.logOther?.(banner);
logger.logProperty?.('cleanMode', cleanMode);
logger.logProperty?.('watchMode', watchMode);
logger.logProperty?.('debugMode', debugMode);
logger.logProperty?.('prettyMode', prettyMode);
if (cleanMode) {
logger.logMethod?.('cleanDist');
await fs.rm(outDir, {recursive: true, force: true});
}
const copyPromise = fs.cp(resDir, outDir, {recursive: true, force: true, dereference: true});
const esbuildContext = await esbuild.context({
entryPoints: [`${srcDir}/${srcFilename}.ts`],
logLevel: 'info',
platform: 'browser',
target: 'es2018',
format: 'esm',
conditions: debugMode ? ['development'] : undefined,
minify: !prettyMode,
treeShaking: true,
sourcemap: true,
sourcesContent: debugMode,
bundle: true,
splitting: true,
charset: 'utf8',
legalComments: 'none',
metafile: true,
define: {
_ALWATR_VERSION_: `'${packageJson.version}+${gitShortSha}'`,
},
// drop: ['debugger'],
loader: {
'.png': 'copy',
'.jpg': 'copy',
'.woff': 'copy',
'.woff2': 'copy',
'.svg': 'text',
'.scss': 'css',
},
banner: {
js: banner,
css: banner,
},
plugins: [
postCssPlugin({
plugins: [postcssImport, postcssNesting, postcssTailwind, postcssPresetEnv],
}),
],
outbase: srcDir,
outdir: outDir,
assetNames: 'asset/[name]-[hash]',
entryNames: watchMode ? '[name]' : '[dir]/[name]-[hash]',
chunkNames: 'chunks/[name]-[hash]',
});
const esBuildPromise = esbuildContext.rebuild();
async function makeHtml() {
logger.logMethod?.('makeHtml');
let htmlContent = await fs.readFile(`${resDir}/index.html`, {encoding: 'utf-8'});
const metafile = (await esBuildPromise).metafile;
const outFiles = Object.keys(metafile.outputs);
const jsFilename = outFiles
.find((filename) => filename.includes(srcFilename) && filename.endsWith('.js'))
.substring(outDir.length + 1);
const cssFilename = outFiles
.find((filename) => filename.includes(srcFilename) && filename.endsWith('.css'))
.substring(outDir.length + 1);
logger.logProperty?.('jsFilename', jsFilename);
logger.logProperty?.('cssFilename', cssFilename);
if (!existsSync(`${outDir}/${jsFilename}`)) {
logger.error('makeHtml', 'js_filename_not_found', {jsFilename});
throw new Error('js_filename_not_found');
}
if (!existsSync(`${outDir}/${cssFilename}`)) {
logger.error('makeHtml', 'css_filename_not_found', {cssFilename});
throw new Error('css_filename_not_found');
}
htmlContent = htmlContent.replaceAll(`${srcFilename}.css`, cssFilename).replaceAll(`${srcFilename}.js`, jsFilename);
await copyPromise; // wait to cp done
await fs.writeFile(`${outDir}/index.html`, htmlContent, {encoding: 'utf-8', flag: 'w'});
}
async function buildServiceWorker() {
logger.logMethod?.('buildServiceWorker');
const build = await generateSW({
swDest: `${outDir}/service-worker.js`,
globDirectory: `${outDir}/`,
clientsClaim: true,
skipWaiting: true,
globPatterns: ['**/*.{js,css,json,png,svg,ico,webp,woff2,html}'],
});
logger.logOther?.('serviceWorkerPath', build);
}
if (watchMode) {
esbuildContext.watch();
} else {
await makeHtml();
esbuildContext.dispose();
if (debugMode) {
console.log(await esbuild.analyzeMetafile((await esBuildPromise).metafile));
}
await buildServiceWorker(); // makeHtml must be done first
}
// /*
// TODO:
// - Input Config
// - Workbox and sw
// - Res (all assets) hash
// - Dynamic from @alwatr/build
// - sideEffects
// https://esbuild.github.io/api/#ignore-annotations
// https://webpack.js.org/guides/tree-shaking/
// - readme
// https://esbuild.github.io/api/#write
// https://github.com/fakundo/esbuild-plugin-replace-regex/blob/master/src/index.js#L30
// https://github.com/zandaqo/esbuild-plugin-lit/blob/master/css-loader.ts
// https://github.com/chialab/rna/tree/main/packages/esbuild-plugin-html
// */