/
webpack.config.js
653 lines (616 loc) · 27.3 KB
/
webpack.config.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
const { dirname, join, relative, resolve, sep } = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const TerserPlugin = require('terser-webpack-plugin');
const nsWebpack = require('nativescript-dev-webpack');
const nativescriptTarget = require('nativescript-dev-webpack/nativescript-target');
const { NativeScriptWorkerPlugin } = require('nativescript-worker-loader/NativeScriptWorkerPlugin');
const hashSalt = Date.now().toString();
const mergeOptions = require('merge-options');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const svelteNativePreprocessor = require('svelte-native-preprocessor');
const { existsSync, mkdirSync, readFileSync } = require('fs');
const SentryCliPlugin = require('@sentry/webpack-plugin');
module.exports = (env, params = {}) => {
// Add your custom Activities, Services and other android app components here.
const appComponents = ['tns-core-modules/ui/frame', 'tns-core-modules/ui/frame/activity'].concat(params.appComponents || []);
console.log('appComponents', appComponents);
const platform = env && ((env.android && 'android') || (env.ios && 'ios'));
if (!platform) {
throw new Error('You need to provide a target platform!');
}
const platforms = ['ios', 'android'];
const projectRoot = params.projectRoot || __dirname;
console.log('projectRoot', projectRoot);
let tsconfig = params.tsconfig;
if (!tsconfig) {
tsconfig = 'tsconfig.json';
if (existsSync(resolve(projectRoot, `tsconfig.${platform}.json`))) {
tsconfig = `tsconfig.${platform}.json`;
}
}
console.log('tsconfig', tsconfig);
// Default destination inside platforms/<platform>/...
const dist = resolve(projectRoot, nsWebpack.getAppPath(platform, projectRoot));
// const appResourcesPlatformDir = platform === 'android' ? 'Android' : 'iOS';
const {
// The 'appPath' and 'appResourcesPath' values are fetched from
// the nsconfig.json configuration file
// when bundling with `tns run android|ios --bundle`.
appPath = 'app',
appResourcesPath = 'app/App_Resources',
development = false,
// You can provide the following flags when running 'tns run android|ios'
snapshot, // --env.snapshot
uglify, // --env.uglify
production, // --env.production
report, // --env.report
hmr, // --env.hmr
sourceMap, // --env.sourceMap
hiddenSourceMap, // --env.hiddenSourceMap
inlineSourceMap, // --env.inlineSourceMap
unitTesting, // --env.unitTesting
verbose, // --env.verbose
snapshotInDocker, // --env.snapshotInDocker
skipSnapshotTools, // --env.skipSnapshotTools
compileSnapshot, // --env.compileSnapshots
sentry, // --env.sentry
includeDarkSkyKey, // --env.includeDarkSkyKey
includeClimaCellKey, // --env.includeClimaCellKey
includeDefaultLocation, // --env.includeDefaultLocation
devlog, // --env.devlog
adhoc // --env.adhoc
} = env;
if (adhoc) {
env = Object.assign({}, env, {
production: true,
sentry: true,
sourceMap: true,
uglify: true
});
}
const useLibs = compileSnapshot;
const isAnySourceMapEnabled = !!sourceMap || !!hiddenSourceMap || !!inlineSourceMap;
const externals = nsWebpack.getConvertedExternals(env.externals);
const mode = production ? 'production' : 'development';
const appFullPath = resolve(projectRoot, appPath);
const hasRootLevelScopedModules = nsWebpack.hasRootLevelScopedModules({
projectDir: projectRoot
});
const alias = mergeOptions(
{
'~': appFullPath,
'@': appFullPath,
},
params.alias || {}
);
console.log('Aliases', alias);
let coreModulesPackageName = 'tns-core-modules';
if (hasRootLevelScopedModules) {
coreModulesPackageName = '@nativescript/core';
alias['tns-core-modules'] = coreModulesPackageName;
}
const appResourcesFullPath = resolve(projectRoot, appResourcesPath);
const entryModule = nsWebpack.getEntryModule(appFullPath, platform);
const entryPath = `.${sep}${entryModule}`;
const entries = mergeOptions({ bundle: entryPath }, params.entries || {});
const areCoreModulesExternal = Array.isArray(env.externals) && env.externals.some(e => e.indexOf('tns-core-modules') > -1);
if (platform === 'ios' && !areCoreModulesExternal) {
entries['tns_modules/tns-core-modules/inspector_modules'] = 'inspector_modules';
}
// if (platform === 'android') {
// entries['application'] = './application.android';
// }
console.log(`Bundling application for entryPath ${entryPath}...`);
const itemsToClean = [`${dist}/**/*`];
if (platform === 'android') {
itemsToClean.push(`${join(projectRoot, 'platforms', 'android', 'app', 'src', 'main', 'assets', 'snapshots')}`);
itemsToClean.push(`${join(projectRoot, 'platforms', 'android', 'app', 'build', 'configurations', 'nativescript-android-snapshot')}`);
}
console.log('itemsToClean', itemsToClean);
// const babelLoader = {
// loader: 'babel-loader',
// options: mergeOptions.call(
// { concatArrays: true },
// {
// cacheDirectory: true,
// presets: [
// [
// '@babel/preset-env',
// {
// modules: false,
// targets: {
// node: '8' // <--- this
// }
// // loose: true
// }
// ]
// ],
// plugins: ['@babel/plugin-syntax-dynamic-import']
// },
// params.babelOptions || {}
// )
// };
const defines = mergeOptions(
{
PRODUCTION: !!production,
process: 'global.process',
'global.TNS_WEBPACK': 'true',
'gVars.platform': `"${platform}"`,
'gVars.isIOS': platform === 'ios',
'gVars.isAndroid': platform === 'android',
TNS_ENV: JSON.stringify(mode),
'gVars.sentry': !!sentry,
SENTRY_DSN: `"${process.env.SENTRY_DSN}"`,
SENTRY_PREFIX: `"${!!sentry ? process.env.SENTRY_PREFIX : ''}"`,
OWM_KEY: `"${process.env.OWM_KEY}"`,
DARK_SKY_KEY: includeDarkSkyKey ? `"${process.env.DARK_SKY_KEY}"` : 'undefined',
CLIMA_CELL_KEY: includeClimaCellKey ? `"${process.env.CLIMA_CELL_KEY}"` : 'undefined',
DEFAULT_LOCATION: includeDefaultLocation ? '\'{"name":"Grenoble","sys":{"osm_id":80348,"osm_type":"R","extent":[5.6776059,45.2140762,5.7531176,45.1541442],"country":"France","osm_key":"place","osm_value":"city","name":"Grenoble","state":"Auvergne-Rhône-Alpes"},"coord":{"lat":45.1875602,"lon":5.7357819}}\'' : 'undefined',
LOG_LEVEL: devlog ? '"full"' : '""',
TEST_LOGS: adhoc || !production
},
params.definePlugin || {}
);
console.log('defines', defines);
const symbolsParser = require('scss-symbols-parser');
const mdiSymbols = symbolsParser.parseSymbols(readFileSync(resolve(projectRoot, 'node_modules/@mdi/font/scss/_variables.scss')).toString());
const mdiIcons = JSON.parse(`{${mdiSymbols.variables[mdiSymbols.variables.length - 1].value.replace(/" (F|0)(.*?)([,\n]|$)/g, '": "$1$2"$3')}}`);
const forecastSymbols = symbolsParser.parseSymbols(readFileSync(resolve(projectRoot, 'app/css/forecastfont.scss')).toString());
const forecastIcons = JSON.parse(`{${forecastSymbols.variables[forecastSymbols.variables.length - 1].value.replace(/'forecastfont-(\w+)' (F|f|0)(.*?)([,\n]|$)/g, '"$1": "$2$3"$4')}}`);
const weatherIconsCss = resolve(projectRoot, 'app/css/weather-icons/weather-icons-variables.scss');
const weatherSymbols = symbolsParser.parseSymbols(readFileSync(weatherIconsCss).toString()).imports.reduce(function(acc, value) {
return acc.concat(symbolsParser.parseSymbols(readFileSync(resolve(dirname(weatherIconsCss), value.filepath)).toString()).variables);
}, []);
// console.log('weatherSymbols', weatherSymbols);
const weatherIcons = weatherSymbols.reduce(function(acc, value) {
acc[value.name.slice(1)] = '\\u' + value.value.slice(2, -1);
return acc;
}, {});
// console.log('weatherIcons', weatherIcons);
const scssPrepend = `$lato-fontFamily: ${platform === 'android' ? 'res/lato' : 'Lato'};
$forecastfont-fontFamily: ${platform === 'android' ? 'iconvault_forecastfont' : 'iconvault'};
$wi-fontFamily: ${platform === 'android' ? 'weathericons-regular-webfont' : 'Weather Icons'};
$mdi-fontFamily: ${platform === 'android' ? 'materialdesignicons-webfont' : 'Material Design Icons'};`;
// console.log('scssPrepend', scssPrepend);
nsWebpack.processAppComponents(appComponents, platform);
const config = {
mode,
context: appFullPath,
externals: externals.concat(params.externals || []),
// stats: 'verbose',
watchOptions: {
ignored: [
appResourcesFullPath,
// Don't watch hidden files
'**/.*'
]
},
target: nativescriptTarget,
entry: entries,
output: {
pathinfo: false,
path: dist,
libraryTarget: 'commonjs2',
filename: '[name].js',
globalObject: 'global',
hashSalt
},
resolve: {
extensions: ['.mjs', '.js', '.ts', '.svelte', '.scss', '.css'],
// Resolve {N} system modules from tns-core-modules
modules: [resolve(projectRoot, `node_modules/${coreModulesPackageName}`), resolve(projectRoot, 'node_modules'), `node_modules/${coreModulesPackageName}`, 'node_modules'],
// mainFields: ['main'],
alias,
// resolve symlinks to symlinked modules
symlinks: true
},
resolveLoader: {
// don't resolve symlinks to symlinked loaders
symlinks: false
},
node: {
// Disable node shims that conflict with NativeScript
http: false,
timers: false,
setImmediate: false,
fs: 'empty',
crypto: 'empty',
__dirname: false
},
devtool: inlineSourceMap ? 'inline-cheap-source-map' : false,
optimization: {
runtimeChunk: 'single',
noEmitOnErrors: true,
splitChunks: {
cacheGroups: {
vendor: {
name: 'vendor',
chunks: 'all',
test: module => {
const moduleName = module.nameForCondition ? module.nameForCondition() : '';
return (
/[\\/]node_modules[\\/]/.test(moduleName) ||
/@nativescript\/core/.test(moduleName) ||
/nativescript-core/.test(moduleName) || // this one is for linked nativescript core build
appComponents.some(comp => comp === moduleName) ||
(params.chunkTestCallback && params.chunkTestCallback(moduleName))
);
},
enforce: true
}
}
},
minimize: uglify !== undefined ? uglify : production,
minimizer: [
new TerserPlugin(
mergeOptions(
{
parallel: true,
cache: true,
sourceMap: isAnySourceMapEnabled,
terserOptions: {
ecma: 6,
// warnings: true,
// toplevel: true,
output: {
comments: false,
semicolons: !isAnySourceMapEnabled
},
compress: {
// The Android SBG has problems parsing the output
// when these options are enabled
collapse_vars: platform !== 'android',
sequences: platform !== 'android',
passes: 2
},
keep_fnames: true
}
},
params.terserOptions || {}
)
)
]
},
module: {
rules: [
{
// test: new RegExp(entryPath + '.(js|ts)'),
include: [join(appFullPath, entryPath + '.js'), join(appFullPath, entryPath + '.ts')],
use: [
// Require all Android app components
platform === 'android' && {
loader: 'nativescript-dev-webpack/android-app-components-loader',
options: { modules: appComponents }
},
{
loader: 'nativescript-dev-webpack/bundle-config-loader',
options: {
// registerPages: true, // applicable only for non-angular apps
loadCss: !snapshot, // load the application css if in debug mode
unitTesting,
appFullPath,
projectRoot,
ignoredFiles: nsWebpack.getUserDefinedEntries(entries, platform)
}
}
].filter(loader => Boolean(loader))
},
{
// rules to replace mdi icons and not use nativescript-font-icon
test: /\.(ts|js|css|svelte)$/,
exclude: /node_modules/,
use: [
{
loader: 'string-replace-loader',
options: {
search: 'mdi-([a-z-]+)',
replace: (match, p1, offset, string) => {
if (mdiIcons[p1]) {
return String.fromCharCode(parseInt(mdiIcons[p1], 16));
}
return match;
},
flags: 'g'
}
},
{
loader: 'string-replace-loader',
options: {
search: 'forecastfont-([a-z-]+)',
replace: (match, p1, offset, string) => {
if (forecastIcons[p1]) {
return String.fromCharCode(parseInt(forecastIcons[p1], 16));
}
return match;
},
flags: 'g'
}
},
{
loader: 'string-replace-loader',
options: {
search: 'wi-([a-z0-9-]+)',
replace: (match, p1, offset, string) => weatherIcons[p1] || match,
flags: 'g'
}
}
]
},
{
test: /\.(ts|css|scss|html|xml)$/,
use: 'nativescript-dev-webpack/hmr/hot-loader'
},
{ test: /\.(html|xml)$/, use: 'nativescript-dev-webpack/xml-namespace-loader' },
{
test: /\.css$/,
use: 'nativescript-dev-webpack/css2json-loader'
},
{
test: /\.scss$/,
exclude: /\.module\.scss$/,
use: [
{
loader: 'nativescript-dev-webpack/css2json-loader',
options: { useForImports: true }
},
{
loader: 'sass-loader',
options: {
sourceMap: false,
data: scssPrepend
}
}
]
},
{
test: /\.module\.scss$/,
use: [
{ loader: 'css-loader', options: { url: false } },
{
loader: 'sass-loader',
options: {
sourceMap: false,
data: scssPrepend
}
}
]
},
// {
// test: /\.js$/,
// // exclude: /node_modules/,
// use: [
// {
// loader: 'string-replace-loader',
// options: {
// search: '\\/\\*\\* @class \\*\\/',
// replace: '/*@__PURE__*/',
// flags: 'g'
// }
// }
// ]
// },
{
test: /\.mjs$/,
type: 'javascript/auto'
},
{
test: /\.ts$/,
exclude: /node_modules/,
use: {
loader: 'ts-loader',
options: {
configFile: resolve(tsconfig),
transpileOnly: true,
allowTsInNodeModules: true,
compilerOptions: {
sourceMap: isAnySourceMapEnabled,
declaration: false
}
}
}
},
{
test: /\.svelte$/,
exclude: /node_modules/,
use: [
{
loader: 'svelte-loader-hot',
options: {
preprocess: require('svelte-preprocess')(
Object.assign(
{
typescript: {
compilerOptions: {
module: 'es6'
}
}
},
svelteNativePreprocessor()
)
),
hotReload: hmr,
hotOptions: {
native: hmr
}
}
}
]
}
]
},
plugins: [
// Define useful constants like TNS_WEBPACK
new webpack.EnvironmentPlugin(
mergeOptions(
{
NODE_ENV: JSON.stringify(mode), // use 'development' unless process.env.NODE_ENV is defined
DEBUG: false
},
params.environmentPlugin || {}
)
),
new webpack.DefinePlugin(defines),
// Remove all files from the out dir.
new CleanWebpackPlugin({
dangerouslyAllowCleanPatternsOutsideProject: true,
dry: false,
verbose: !!verbose,
cleanOnceBeforeBuildPatterns: itemsToClean
}),
// Copy assets to out dir. Add your own globs as needed.
new CopyWebpackPlugin(
[
{ from: 'fonts/!(ios|android)/**/*', to: 'fonts', flatten: true },
{ from: 'fonts/*', to: 'fonts', flatten: true },
{ from: `fonts/${platform}/**/*`, to: 'fonts', flatten: true },
{ from: '**/*.+(jpg|png)' },
{ from: 'assets/**/*' },
{
from: '../node_modules/@mdi/font/fonts/materialdesignicons-webfont.ttf',
to: 'fonts'
// },
// {
// from: '../node_modules/weather-icons/font/weathericons-regular-webfont.ttf',
// to: 'fonts'
}
].concat(params.copyPlugin || []),
{
ignore: [`${relative(appPath, appResourcesFullPath)}/**`]
}
),
// we use platform name to identify ios/android files in Sentry
new nsWebpack.GenerateNativeScriptEntryPointsPlugin('bundle'),
// For instructions on how to set up workers with webpack
// check out https://github.com/nativescript/worker-loader
new NativeScriptWorkerPlugin(),
new nsWebpack.PlatformFSPlugin({
platform,
platforms
}),
// Does IPC communication with the {N} CLI to notify events when running in watch mode.
new nsWebpack.WatchStateLoggerPlugin()
]
};
if (hiddenSourceMap || sourceMap) {
if (!!sentry) {
// const sourceMapFilename = nsWebpack.getSourceMapFilename(hiddenSourceMap, __dirname, dist);
config.plugins.push(
new webpack.SourceMapDevToolPlugin(
mergeOptions(
{
append: `\n//# sourceMappingURL=${process.env.SENTRY_PREFIX}[name].js.map`,
filename: join(process.env.SOURCEMAP_REL_DIR, '[name].js.map')
},
params.sourceMapPlugin || {}
)
)
);
let appVersion;
let buildNumber;
if (platform === 'android') {
appVersion = readFileSync('app/App_Resources/Android/app.gradle', 'utf8').match(/versionName "((?:[0-9]+\.?)+)"/)[1];
buildNumber = readFileSync('app/App_Resources/Android/app.gradle', 'utf8').match(/versionCode ([0-9]+)/)[1];
} else if (platform === 'ios') {
appVersion = readFileSync('app/App_Resources/iOS/Info.plist', 'utf8').match(/<key>CFBundleShortVersionString<\/key>[\s\n]*<string>(.*?)<\/string>/)[1];
buildNumber = readFileSync('app/App_Resources/iOS/Info.plist', 'utf8').match(/<key>CFBundleVersion<\/key>[\s\n]*<string>([0-9]*)<\/string>/)[1];
}
console.log('appVersion', appVersion, buildNumber);
config.plugins.push(
new SentryCliPlugin({
release: appVersion,
urlPrefix: 'app:///',
rewrite: true,
dist: `${buildNumber}.${platform}`,
ignore: ['tns-java-classes', 'hot-update'],
include: [dist, join(dist, process.env.SOURCEMAP_REL_DIR)]
})
);
} else {
config.plugins.push(
new webpack.SourceMapDevToolPlugin(
mergeOptions(
{
noSources: true
// fileContext:params.sourceMapPublicPath
// publicPath: params.sourceMapPublicPath || '~/',
// fileContext:sourceMapsDist,
// noSources:true,
// moduleFilenameTemplate: info => {
// let filePath = info.identifier;
// console.log( 'filePath', filePath);
// if (filePath.startsWith('./')) {
// filePath = './app' + filePath.slice(1);
// }
// // if (filePath.startsWith('file:///')) {
// // filePath = './app' + filePath.slice(1);
// // }
// return filePath.replace('file:///', '');
// }
},
params.sourceMapPlugin || {}
)
)
);
}
}
if (unitTesting) {
config.module.rules.push(
{
test: /-page\.js$/,
use: 'nativescript-dev-webpack/script-hot-loader'
},
{
test: /\.(ts|css|scss|html|xml)$/,
use: 'nativescript-dev-webpack/hmr/hot-loader'
},
{
test: /\.(html|xml)$/,
use: 'nativescript-dev-webpack/xml-namespace-loader'
}
);
}
if (!!report) {
// Generate report files for bundles content
config.plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
reportFilename: resolve(projectRoot, 'report', 'report.html')
})
);
}
if (!!snapshot) {
const options = mergeOptions(
{
chunk: 'vendor',
requireModules: ['tns-core-modules/bundle-entry-points'],
projectRoot,
// targetArchs: params.targetArchs || ['arm'],
snapshotInDocker,
skipSnapshotTools,
useLibs
},
params.snapshotPlugin
);
config.plugins.push(new nsWebpack.NativeScriptSnapshotPlugin(Object.assign(options, { webpackConfig: config })));
}
if (!!hmr) {
config.plugins.push(new webpack.HotModuleReplacementPlugin());
}
// if (!!production) {
// config.plugins.push(
// new ForkTsCheckerWebpackPlugin({
// tsconfig: resolve(tsconfig),
// async: false,
// useTypescriptIncrementalApi: true,
// checkSyntacticErrors: true,
// memoryLimit: 4096,
// workers: 1
// })
// );
// }
return config;
};