-
-
Notifications
You must be signed in to change notification settings - Fork 201
/
esbuild.js
191 lines (163 loc) · 5.02 KB
/
esbuild.js
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
const esbuild = require('esbuild')
const { cp, stat, readFile, writeFile } = require('fs/promises')
const { exists, emptyDir } = require('fs-extra')
const { join } = require('path')
const outputDir = 'build'
function cleanPkgJson(json) {
delete json.devDependencies
delete json['release-it']
delete json.optionalDependencies
delete json.dependencies
return json
}
/**
* Remove useless fields from package.json, this is needed mostly for `pkg`
* otherwise it will try to bundle dependencies
*/
async function patchPkgJson(path) {
const pkgJsonPath = join(outputDir, path, 'package.json')
const pkgJson = require('./' + pkgJsonPath)
cleanPkgJson(pkgJson)
delete pkgJson.scripts
await writeFile(pkgJsonPath, JSON.stringify(pkgJson, null, 2))
}
// from https://github.com/evanw/esbuild/issues/1051#issuecomment-806325487
const nativeNodeModulesPlugin = {
name: 'native-node-modules',
setup(build) {
// If a ".node" file is imported within a module in the "file" namespace, resolve
// it to an absolute path and put it into the "node-file" virtual namespace.
build.onResolve({ filter: /\.node$/, namespace: 'file' }, (args) => ({
path: require.resolve(args.path, { paths: [args.resolveDir] }),
namespace: 'node-file',
}))
// Files in the "node-file" virtual namespace call "require()" on the
// path from esbuild of the ".node" file in the output directory.
build.onLoad({ filter: /.*/, namespace: 'node-file' }, (args) => ({
contents: `
import path from ${JSON.stringify(args.path)}
try { module.exports = require(path) }
catch {}
`,
}))
// If a ".node" file is imported within a module in the "node-file" namespace, put
// it in the "file" namespace where esbuild's default loading behavior will handle
// it. It is already an absolute path since we resolved it to one above.
build.onResolve(
{ filter: /\.node$/, namespace: 'node-file' },
(args) => ({
path: args.path,
namespace: 'file',
}),
)
// Tell esbuild's default loading behavior to use the "file" loader for
// these ".node" files.
let opts = build.initialOptions
opts.loader = opts.loader || {}
opts.loader['.node'] = 'file'
},
}
async function printSize(fileName) {
const stats = await stat(fileName)
// print size in MB
console.log(`Bundle size: ${Math.round(stats.size / 10000) / 100}MB\n\n`)
}
async function main() {
const start = Date.now()
// clean build folder
await emptyDir(outputDir)
const outfile = `${outputDir}/index.js`
const externals = [
'@serialport/bindings-cpp/prebuilds',
'zwave-js/package.json',
'@zwave-js/server/package.json',
'@zwave-js/config/package.json',
'@zwave-js/config/config',
'@zwave-js/config/build',
'./snippets',
'./dist',
]
/** @type { import('esbuild').BuildOptions } */
const config = {
entryPoints: [
process.argv.includes('--js-entrypoint')
? 'server/bin/www.js'
: 'api/bin/www.ts',
],
plugins: [nativeNodeModulesPlugin],
bundle: true,
platform: 'node',
target: 'node18',
sourcemap: process.argv.includes('--sourcemap'),
outfile,
// suppress direct-eval warning
logOverride: {
'direct-eval': 'silent',
},
external: externals,
// Prevent esbuild from adding a "2" to the names of CC classes for some reason.
keepNames: true,
// Fix import.meta.url in CJS output
define: {
'import.meta.url': '__import_meta_url',
},
inject: ['esbuild-import-meta-url-shim.js'],
}
await esbuild.build(config)
console.log(`Build took ${Date.now() - start}ms`)
await printSize(outfile)
const content = (await readFile(outfile, 'utf-8'))
.replace(
/__dirname, "\.\.\/"/g,
'__dirname, "./node_modules/@serialport/bindings-cpp"',
)
.replace(
`"../../package.json"`,
`"./node_modules/@zwave-js/server/package.json"`,
)
await writeFile(outfile, content)
if (process.argv.includes('--minify')) {
// minify the file
await esbuild.build({
...config,
entryPoints: [outfile],
minify: true,
keepNames: true, // needed for zwave-js as it relies on class names
allowOverwrite: true,
outfile,
})
console.log(`Minify took ${Date.now() - start}ms`)
await printSize(outfile)
}
// copy assets to build folder
for (const ext of externals) {
const path = ext.startsWith('./') ? ext : `node_modules/${ext}`
if (await exists(path)) {
console.log(`Copying "${path}" to "${outputDir}" folder`)
await cp(path, `${outputDir}/${path}`, { recursive: true })
} else {
console.log(`Asset "${path}" does not exist. Skipping...`)
}
}
// create main patched packege.json
const pkgJson = require('./package.json')
cleanPkgJson(pkgJson)
pkgJson.scripts = {
start: 'node index.js',
}
pkgJson.bin = 'index.js'
pkgJson.pkg = {
assets: ['dist/**', 'snippets/**', 'node_modules/**'],
}
await writeFile(
`${outputDir}/package.json`,
JSON.stringify(pkgJson, null, 2),
)
await patchPkgJson('node_modules/@zwave-js/config')
await patchPkgJson('node_modules/zwave-js')
await patchPkgJson('node_modules/@zwave-js/server')
}
main().catch((err) => {
console.error(err)
process.exit(1)
})