-
Notifications
You must be signed in to change notification settings - Fork 311
/
Copy pathwebpack.config.babel.js
347 lines (326 loc) · 10.1 KB
/
webpack.config.babel.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// Copyright © 2024 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* eslint-env node */
import fs from 'fs'
import path from 'path'
import child_process from 'child_process'
import { responseInterceptor } from 'http-proxy-middleware'
import webpack from 'webpack'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import MiniCssExtractPlugin from 'mini-css-extract-plugin'
import AddAssetHtmlPlugin from 'add-asset-html-webpack-plugin'
import { CleanWebpackPlugin } from 'clean-webpack-plugin'
import ShellPlugin from 'webpack-shell-plugin'
import CopyWebpackPlugin from 'copy-webpack-plugin'
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin'
import pjson from '../package.json'
const { version } = pjson
const revision =
child_process.execSync('git rev-parse --short HEAD').toString().trim() || 'unknown revision'
const {
CONTEXT = '.',
CACHE_DIR = '.cache',
PUBLIC_DIR = 'public',
NODE_ENV = 'production',
MAGE = 'tools/bin/mage',
CI = false,
} = process.env
const WEBPACK_IS_DEV_SERVER_BUILD = process.env.WEBPACK_IS_DEV_SERVER_BUILD === 'true'
const WEBPACK_DEV_SERVER_DISABLE_HMR = process.env.WEBPACK_DEV_SERVER_DISABLE_HMR === 'true'
const WEBPACK_DEV_SERVER_USE_TLS = process.env.WEBPACK_DEV_SERVER_USE_TLS === 'true'
const WEBPACK_GENERATE_PRODUCTION_SOURCEMAPS =
process.env.WEBPACK_GENERATE_PRODUCTION_SOURCEMAPS === 'true'
const WEBPACK_DEV_STATIC_ROUTES_PROXY_URL = WEBPACK_DEV_SERVER_USE_TLS
? 'https://localhost:8885'
: 'http://localhost:1885'
const WEBPACK_DEV_BACKEND_API_PROXY_URL =
process.env.WEBPACK_DEV_BACKEND_API_PROXY_URL || WEBPACK_DEV_STATIC_ROUTES_PROXY_URL
const TTN_LW_TLS_CERTIFICATE = process.env.TTN_LW_TLS_CERTIFICATE || './cert.pem'
const TTN_LW_TLS_KEY = process.env.TTN_LW_TLS_KEY || './key.pem'
const TTN_LW_TLS_ROOT_CA = process.env.TTN_LW_TLS_ROOT_CA || './ca.pem'
const WEBPACK_DEV_ADDITIONAL_CONFIG = JSON.parse(
process.env.WEBPACK_DEV_ADDITIONAL_CONFIG || '"{}"',
)
const ADDITIONAL_CONFIG = JSON.parse(WEBPACK_DEV_ADDITIONAL_CONFIG)
const ASSETS_ROOT = '/assets'
const proxyHost = WEBPACK_DEV_BACKEND_API_PROXY_URL.replace(/https?:\/\//, '')
const context = path.resolve(CONTEXT)
const production = NODE_ENV !== 'development'
const src = path.resolve('.', 'pkg/webui')
const include = [src]
const modules = [path.resolve(context, 'node_modules')]
const supportedLocales = fs
.readdirSync(path.resolve(context, 'pkg/webui/locales'))
.filter(fn => fn.endsWith('.json'))
.map(fn => fn.split('.')[0])
const r = supportedLocales.map(l => new RegExp(`./${l.trim()}`))
const filterLocales = (context, request, callback) => {
if (
context.endsWith('node_modules/intl/locale-data/jsonp') ||
context.endsWith('node_modules/@formatjs/intl-relativetimeformat/locale-data')
) {
const supported = r.reduce((acc, locale) => acc || locale.test(request), false)
if (!supported) {
return callback(null, `commonjs ${request}`)
}
}
callback()
}
// Env selects and merges the environments for the passed object based on
// `NODE_ENV`, which can have the all, development and production keys.
const env = (obj = {}) => {
if (!obj) {
return obj
}
const all = obj.all
const dev = obj.development
const prod = obj.production
if (Array.isArray(all) || Array.isArray(dev) || Array.isArray(prod)) {
return [...(all || []), ...(production ? prod || [] : dev || [])]
}
if (
(dev !== undefined && typeof dev !== 'object') ||
(prod !== undefined && typeof prod !== 'object')
) {
return production ? prod : dev
}
return {
...(all || {}),
...(production ? prod || {} : dev || {}),
}
}
export const styleConfig = {
test: /\.(styl|css)$/,
include,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: './',
},
},
{
loader: 'css-loader',
options: {
modules: {
exportLocalsConvention: 'camelCase',
localIdentName: env({
production: '[hash:base64:4]',
development: '[local]-[hash:base64:4]',
}),
},
},
},
{
loader: 'stylus-loader',
options: {
stylusOptions: {
import: [path.resolve(context, 'pkg/webui/styles/include.styl')],
},
},
},
],
}
export default {
context,
mode: production ? 'production' : 'development',
externals: [filterLocales],
stats: 'minimal',
target: 'web',
devtool: production ? false : 'eval-source-map',
resolve: {
alias: env({
all: {
'@ttn-lw': path.resolve(context, 'pkg/webui'),
'@console': path.resolve(context, 'pkg/webui/console'),
'@account': path.resolve(context, 'pkg/webui/account'),
'@assets': path.resolve(context, 'pkg/webui/assets'),
},
development: {
'ttn-lw': path.resolve(context, 'sdk/js/src'),
},
}),
},
devServer: {
devMiddleware: {
publicPath: `${ASSETS_ROOT}/`,
},
port: 8080,
hot: !WEBPACK_DEV_SERVER_DISABLE_HMR,
proxy: [
{
context: ['/console', '/account', '/assets/blob'],
target: WEBPACK_DEV_STATIC_ROUTES_PROXY_URL,
changeOrigin: true,
secure: false,
ws: true,
},
{
context: ['/api', '/oauth'],
target: WEBPACK_DEV_BACKEND_API_PROXY_URL,
changeOrigin: true,
secure: false,
ws: true,
selfHandleResponse: true,
onProxyRes: responseInterceptor(async responseBuffer => {
// Replace occurrences of the proxyhost with localhost:8080.
// Otherwise, many entities will appear as "Other cluster".
const response = responseBuffer
.toString('utf8')
.replace(new RegExp(proxyHost, 'g'), 'localhost')
return response
}),
},
],
historyApiFallback: true,
...(WEBPACK_DEV_SERVER_USE_TLS
? {
https: {
cert: fs.readFileSync(TTN_LW_TLS_CERTIFICATE),
key: fs.readFileSync(TTN_LW_TLS_KEY),
ca: fs.readFileSync(TTN_LW_TLS_ROOT_CA),
},
}
: {}),
},
entry: {
console: ['./config/root.js', './pkg/webui/console.js'],
account: ['./config/root.js', './pkg/webui/account.js'],
},
output: {
filename: production ? '[name].[chunkhash].js' : '[name].js',
chunkFilename: production ? '[name].[chunkhash].js' : '[name].js',
path: path.resolve(context, PUBLIC_DIR),
crossOriginLoading: 'anonymous',
publicPath: ASSETS_ROOT,
},
optimization: {
splitChunks: {
cacheGroups: {
styles: {
name: 'styles',
test: /\.css$/,
chunks: 'all',
},
},
},
removeEmptyChunks: false,
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
include,
options: {
cacheDirectory: path.resolve(context, CACHE_DIR, 'babel'),
sourceMap: true,
babelrc: true,
plugins: [
!WEBPACK_DEV_SERVER_DISABLE_HMR &&
!production &&
require.resolve('react-refresh/babel'),
].filter(Boolean),
},
},
{
test: /\.(woff|woff2|ttf|eot|otf|jpg|jpeg|png|svg)$/i,
type: 'asset/resource',
generator: {
filename: '[name].[contenthash:20][ext]',
},
},
styleConfig,
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: false,
},
},
],
include: modules,
},
],
},
plugins: env({
all: [
new webpack.EnvironmentPlugin({
NODE_ENV,
CI,
VERSION: version,
REVISION: revision,
ADDITIONAL_CONFIG: JSON.stringify(ADDITIONAL_CONFIG),
}),
new webpack.DefinePlugin({
'process.predefined.SUPPORTED_LOCALES': JSON.stringify(supportedLocales),
}),
new HtmlWebpackPlugin({
inject: false,
filename: `manifest.yaml`,
showErrors: false,
template: path.resolve('config', 'manifest-template.yaml'),
minify: false,
}),
new MiniCssExtractPlugin({
filename: env({
development: '[name].css',
production: '[name].[contenthash].css',
}),
}),
new CleanWebpackPlugin({
dry: WEBPACK_IS_DEV_SERVER_BUILD,
verbose: false,
cleanOnceBeforeBuildPatterns: env({
all: ['**/*'],
development: ['!libs.bundle.js', '!libs.bundle.js.map'],
production: ['!libs.*.bundle.js', '!libs.*.bundle.js.map'],
}),
}),
new CopyWebpackPlugin({
patterns: [{ from: `${src}/assets/static` }],
}),
new webpack.DllReferencePlugin({
context,
manifest: path.resolve(context, CACHE_DIR, 'dll.json'),
}),
new AddAssetHtmlPlugin({
glob: path.resolve(context, PUBLIC_DIR, 'libs*bundle.js'),
}),
],
production: [
...(WEBPACK_GENERATE_PRODUCTION_SOURCEMAPS
? [
new webpack.SourceMapDevToolPlugin({
filename: '[file].map',
exclude: /^(?!(console|oauth).*$).*/,
}),
]
: []),
],
development: [
...(!WEBPACK_DEV_SERVER_DISABLE_HMR ? [new ReactRefreshWebpackPlugin()] : []),
new webpack.WatchIgnorePlugin({
paths: [/node_modules/, /locales/, path.resolve(context, PUBLIC_DIR)],
}),
new ShellPlugin({
onBuildExit: [`${MAGE} js:extractLocaleFiles`],
}),
],
}),
}