forked from shadowwalker/next-pwa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build-custom-worker.js
120 lines (110 loc) · 3.08 KB
/
build-custom-worker.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
'use strict'
const path = require('path')
const fs = require('fs')
const webpack = require('webpack')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const buildCustomWorker = ({ id, basedir, customWorkerDir, destdir, plugins, minify }) => {
let workerDir = undefined
if (fs.existsSync(path.join(basedir, customWorkerDir))) {
workerDir = path.join(basedir, customWorkerDir)
} else if (fs.existsSync(path.join(basedir, 'src', customWorkerDir))) {
workerDir = path.join(basedir, 'src', customWorkerDir)
}
if (!workerDir) return
const name = `worker-${id}.js`
const customWorkerEntries = ['ts', 'js']
.map(ext => path.join(workerDir, `index.${ext}`))
.filter(entry => fs.existsSync(entry))
if (customWorkerEntries.length === 0) return
if (customWorkerEntries.length > 1) {
console.warn(
`> [PWA] WARNING: More than one custom worker found (${customWorkerEntries.join(
','
)}), not building a custom worker`
)
return
}
const customWorkerEntry = customWorkerEntries[0]
console.log(`> [PWA] Custom worker found: ${customWorkerEntry}`)
console.log(`> [PWA] Build custom worker: ${path.join(destdir, name)}`)
webpack({
mode: 'none',
target: 'webworker',
entry: {
main: customWorkerEntry
},
resolve: {
extensions: ['.ts', '.js'],
fallback: {
module: false,
dgram: false,
dns: false,
path: false,
fs: false,
os: false,
crypto: false,
stream: false,
http2: false,
net: false,
tls: false,
zlib: false,
child_process: false
}
},
module: {
rules: [
{
test: /\.(t|j)s$/i,
use: [
{
loader: 'babel-loader',
options: {
presets: [
[
'next/babel',
{
'transform-runtime': {
corejs: false,
helpers: true,
regenerator: false,
useESModules: true
},
'preset-env': {
modules: false,
targets: 'chrome >= 56'
}
}
]
]
}
}
]
}
]
},
output: {
path: destdir,
filename: name
},
plugins: [
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: [path.join(destdir, 'worker-*.js'), path.join(destdir, 'worker-*.js.map')]
})
].concat(plugins),
optimization: minify
? {
minimize: true,
minimizer: [new TerserPlugin()]
}
: undefined
}).run((error, status) => {
if (error || status.hasErrors()) {
console.error(`> [PWA] Failed to build custom worker`)
console.error(status.toString({ colors: true }))
process.exit(-1)
}
})
return name
}
module.exports = buildCustomWorker