Replace webpack with esbuild

This commit is contained in:
Terncode committed 2026-11-22 18:41:08 +01:00
1 parent 7e3e2dc5b9
commit ecb1b76891
13 files changed
+750 -7990

No files matched your search

+2
View File
@@ -277,6 +277,8 @@ gulp dev # terminal 3
gulp test # terminal 4 (optional)
```
`npm run wds` builds client with JIT and type checks in background, `npm run wds-aot` uses the same AOT compilation as production build (checks templates, slower rebuilds).
```bash
gulp dev --sprites # run with generation of sprite sheets (use src/ts/tools/trigger.txt to trigger sprite generation without restarting gulp)
gulp dev --test # run with tests
+456
View File
@@ -0,0 +1,456 @@
import fs from 'fs';
import path from 'path';
import http from 'http';
import { spawn } from 'child_process';
import crypto from 'crypto';
import { fileURLToPath } from 'url';
import * as esbuild from 'esbuild';
import * as sass from 'sass-embedded';
import swc from '@swc/core';
import remapping from '@jridgewell/remapping';
import pugTemplate from './tools/pug-template.cjs';
const root = path.dirname(fileURLToPath(import.meta.url));
const argv = new Set(process.argv.slice(2));
const argValue = name => process.argv.slice(2).find(a => a.startsWith(`--${name}=`))?.split('=')[1];
const dev = argv.has('--dev');
const jit = dev && !argv.has('--aot');
if (!jit && !global.angularPugHook) {
console.error('AOT build requires: node --require ./tools/angular-pug-hook.cjs build-client.mjs (or npm run client)');
process.exit(1);
}
const { createCompilerPlugin, SourceFileCache, getSupportedBrowsers, transformSupportedBrowsersToTargets } =
jit ? {} : await import('@angular/build/private');
const DEV_PORT = 8091;
const sassDeprecations = ['import', 'global-builtin', 'color-functions', 'if-function', 'slash-div'];
const bundles = [
{ name: 'bootstrap', tsconfig: 'tsconfig-aot.json', outDir: 'assets', tools: false, sourcemap: true },
{ name: 'bootstrap-admin', tsconfig: 'tsconfig-aot-admin.json', outDir: 'assets-admin', tools: true },
{ name: 'bootstrap-tools', tsconfig: 'tsconfig-aot-tools.json', outDir: 'assets', tools: true },
];
function selectBundles() {
const bundle = argValue('bundle');
if (bundle) {
const found = bundles.filter(b => b.name === bundle);
if (!found.length) {
throw new Error(`Unknown bundle: ${bundle}`);
}
return found;
}
else if (argv.has('--tools') || argv.has('--beta')) {
return bundles;
}
else if (argv.has('--main') || argv.has('--analyze')) {
return [bundles[0]];
}
else if (argv.has('--admin')) {
return [bundles[1]];
}
else {
return bundles;
}
}
function getAnalytics() {
const config = JSON.parse(fs.readFileSync(path.join(root, 'config.json'), 'utf8'));
return config.analytics ? `
(function(i, s, o, g, r, a, m) {i['GoogleAnalyticsObject']=r; i[r]=i[r]||function() {
(i[r].q=i[r].q||[]).push(arguments) }, i[r].l=1*new Date(); a=s.createElement(o),
m=s.getElementsByTagName(o)[0]; a.async=1; a.src=g; m.parentNode.insertBefore(a, m)
}) (window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', '${config.analytics.trackingID}', 'auto');
ga('send', 'pageview');
` : '';
}
const lodashPlugin = {
name: 'lodash',
setup(build) {
build.onResolve({ filter: /^lodash$/ }, args => /[\\/]node_modules[\\/]/.test(args.importer) ?
undefined : { path: path.join(root, 'src', 'ts', 'lodash.ts') });
},
};
function createOptions({ entryPoints, tsconfig, defines, sourcemap, cacheName, banner }) {
const cssTarget = transformSupportedBrowsersToTargets(getSupportedBrowsers(root, { warn: message => console.warn(message) }));
const sourceFileCache = new SourceFileCache(path.join(root, '.cache', 'angular', cacheName));
const optimize = !dev;
const angularPlugin = createCompilerPlugin({
tsconfig: path.join(root, tsconfig),
sourcemap: !!sourcemap,
jit: false,
advancedOptimizations: optimize,
thirdPartySourcemaps: false,
incremental: dev,
sourceFileCache,
loadResultCache: sourceFileCache.loadResultCache,
browserOnlyBuild: true,
}, {
workspaceRoot: root,
optimization: optimize,
inlineFonts: false,
sourcemap: false,
outputNames: { bundles: '[name]', media: 'media/[name]' },
includePaths: [path.join(root, 'src', 'styles')],
sass: { silenceDeprecations: sassDeprecations },
target: cssTarget,
inlineStyleLanguage: 'scss',
cacheOptions: {
enabled: true,
basePath: path.join(root, '.cache', 'angular'),
path: path.join(root, '.cache', 'angular', cacheName, 'styles'),
},
});
const options = {
absWorkingDir: root,
entryPoints,
outdir: path.join(root, 'dist', 'client'),
bundle: true,
format: 'iife',
platform: 'browser',
target: 'es2022',
write: false,
metafile: true,
sourcemap: sourcemap ? 'external' : false,
sourcesContent: true,
minify: false,
legalComments: dev ? 'none' : 'eof',
mainFields: ['es2020', 'es2015', 'browser', 'module', 'main'],
conditions: ['es2020', 'es2015', 'module'],
resolveExtensions: ['.ts', '.tsx', '.mjs', '.js', '.cjs'],
tsconfigRaw: {},
define: {
...Object.fromEntries(Object.entries(defines).map(([key, value]) => [key, JSON.stringify(value)])),
global: 'globalThis',
},
banner: banner ? { js: banner } : undefined,
logLevel: 'warning',
plugins: [lodashPlugin, angularPlugin],
};
return { options, sourceFileCache };
}
const minifyOptions = {
ecma: 5,
compress: { ecma: 5, arrows: false },
mangle: {
props: { regex: '^__', reserved: ['__default'] },
},
format: { comments: false },
extractComments: 'some',
};
async function minify(name, code, map) {
if (argv.has('--debug')) {
const result = await esbuild.transform(code, { minify: true, target: 'es2022', sourcemap: !!map, legalComments: 'external' });
return { code: result.code, map: map && remapping([result.map, map], () => null).toString(), comments: result.legalComments };
}
const result = await swc.minify(code, { ...minifyOptions, sourceMap: !!map });
return {
code: result.code,
map: map && remapping([result.map, map], () => null).toString(),
comments: result.extractedComments?.join('\n'),
};
}
async function buildProd(bundle) {
const start = Date.now();
const defines = {
DEVELOPMENT: false,
TOOLS: bundle.tools,
SERVER: false,
BETA: argv.has('--beta'),
TIMING: argv.has('--timing'),
TESTS: false,
ngDevMode: false,
ngJitMode: false,
ngI18nClosureMode: false,
};
const banner = bundle.name === 'bootstrap' && !argv.has('--analyze') ? getAnalytics() : '';
const { options } = createOptions({
entryPoints: { [bundle.name]: `src/ts/${bundle.name}.ts` },
tsconfig: bundle.tsconfig,
defines,
sourcemap: bundle.sourcemap,
cacheName: bundle.name,
banner,
});
const result = await esbuild.build(options);
const js = result.outputFiles.find(f => f.path.endsWith(`${bundle.name}.js`));
const map = result.outputFiles.find(f => f.path.endsWith(`${bundle.name}.js.map`));
const minified = await minify(bundle.name, js.text.replace(/\n\/\/# sourceMappingURL=.*\n?$/, '\n'), map?.text);
const hash = crypto.createHash('md5').update(minified.code).digest('hex').slice(0, 10);
const fileName = `${bundle.name}-${hash}.js`;
const outDir = path.join(root, 'dist', 'browser', bundle.outDir, 'scripts');
fs.mkdirSync(outDir, { recursive: true });
if (minified.map) {
fs.writeFileSync(path.join(outDir, `${fileName}.map`), minified.map);
fs.writeFileSync(path.join(outDir, fileName), `${minified.code}\n//# sourceMappingURL=${fileName}.map`);
}
else {
fs.writeFileSync(path.join(outDir, fileName), minified.code);
}
if (minified.comments) {
fs.writeFileSync(path.join(outDir, `${fileName}.LICENSE.txt`), minified.comments);
}
if (argv.has('--analyze')) {
fs.writeFileSync(path.join(root, 'dist', `${bundle.name}-meta.json`), JSON.stringify(result.metafile));
console.log(await esbuild.analyzeMetafile(result.metafile));
}
const size = (Buffer.byteLength(minified.code) / 1024).toFixed(0);
console.log(`[${bundle.name}] ${path.relative(root, path.join(outDir, fileName))} ${size} KiB in ${((Date.now() - start) / 1000).toFixed(1)}s`);
}
function createJitPlugin() {
const cache = new Map();
const styleCache = new Map();
const plugin = {
name: 'angular-jit',
setup(build) {
build.onLoad({ filter: /\.ts$/ }, async ({ path: file }) => {
if (!cache.has(file)) {
cache.set(file, (async () => {
const imports = [];
const resource = (name, url) => {
const relative = /^\.{0,2}\//.test(url) ? url : `./${url}`;
imports.push(`import __${name}${imports.length} from '${relative}';`);
return `__${name}${imports.length - 1}`;
};
const source = (await fs.promises.readFile(file, 'utf8'))
.replace(/templateUrl:\s*'([^']+)'/g, (_, url) => `template: ${resource('template', url)}`)
.replace(/styleUrls:\s*\[\s*'([^']+)'\s*\]/g, (_, url) => `styles: [${resource('style', url)}]`);
const { code } = await swc.transform(imports.join('') + source, {
filename: file,
sourceMaps: 'inline',
jsc: {
parser: { syntax: 'typescript', decorators: true },
transform: { legacyDecorator: true, decoratorMetadata: true, useDefineForClassFields: true },
target: 'es2022',
},
module: { type: 'commonjs' },
});
return { contents: code, loader: 'js' };
})());
}
try {
return await cache.get(file);
}
catch (e) {
cache.delete(file);
throw e;
}
});
build.onLoad({ filter: /\.pug$/ }, ({ path: file }) => ({ contents: pugTemplate.compilePugTemplate(file), loader: 'text' }));
build.onLoad({ filter: /\.scss$/ }, async ({ path: file }) => {
if (!styleCache.has(file)) {
styleCache.set(file, sass.compileAsync(file, {
loadPaths: [path.join(root, 'src', 'styles')],
quietDeps: true,
silenceDeprecations: sassDeprecations,
}).then(result => ({ contents: result.css, loader: 'text' })));
}
try {
return await styleCache.get(file);
}
catch (e) {
styleCache.delete(file);
throw e;
}
});
},
};
const invalidate = files => {
files.forEach(file => cache.delete(file));
if (files.some(file => file.endsWith('.scss'))) {
styleCache.clear();
}
};
return { plugin, invalidate };
}
function createJitOptions(defines, banner) {
const jit = createJitPlugin();
const options = {
absWorkingDir: root,
entryPoints: Object.fromEntries(bundles.map(b => [b.name, `src/ts/${b.name}.ts`])),
bundle: true,
format: 'iife',
platform: 'browser',
target: 'es2022',
write: false,
mainFields: ['es2020', 'es2015', 'browser', 'module', 'main'],
conditions: ['es2020', 'es2015', 'module'],
resolveExtensions: ['.ts', '.tsx', '.mjs', '.js', '.cjs'],
tsconfigRaw: {},
define: {
...Object.fromEntries(Object.entries(defines).map(([key, value]) => [key, JSON.stringify(value)])),
global: 'globalThis',
},
banner: { js: banner },
logLevel: 'warning',
plugins: [lodashPlugin, jit.plugin],
};
return { options, invalidate: jit.invalidate };
}
function startTypeCheck() {
const tsc = spawn(process.execPath, [
path.join(root, 'node_modules', 'typescript-7', 'bin', 'tsc'),
'-p', 'tsconfig-aot-dev.json', '--noEmit', '--watch', '--preserveWatchOutput', '--pretty',
], { cwd: root, stdio: 'inherit' });
const kill = () => tsc.kill();
process.on('exit', kill);
['SIGINT', 'SIGTERM'].forEach(signal => process.on(signal, () => process.exit()));
}
const reloadBanner = `(() => {
const src = document.currentScript && document.currentScript.src;
if (src && typeof EventSource !== 'undefined') {
new EventSource(new URL('/reload', src)).onmessage = () => location.reload();
}
})();`;
async function runDev() {
const devDir = path.join(root, '.cache', 'dev-client');
const defines = { DEVELOPMENT: true, TOOLS: true, SERVER: false, BETA: true, TIMING: true, TESTS: false };
let options;
let invalidate;
if (!jit) {
let sourceFileCache;
({ options, sourceFileCache } = createOptions({
entryPoints: Object.fromEntries(bundles.map(b => [b.name, `src/ts/${b.name}.ts`])),
tsconfig: 'tsconfig-aot-dev.json',
defines,
sourcemap: true,
cacheName: 'dev',
banner: reloadBanner,
}));
invalidate = files => sourceFileCache.invalidate(files);
}
else {
({ options, invalidate } = createJitOptions(defines, reloadBanner));
startTypeCheck();
}
options.outdir = path.join(devDir, 'assets', 'scripts');
options.sourcemap = 'linked';
const files = new Map();
const reloadClients = new Set();
const context = await esbuild.context(options);
let building = Promise.resolve();
const rebuild = (changed = []) => {
building = building.then(async () => {
const start = Date.now();
if (changed.length) {
invalidate(changed);
}
try {
const result = await context.rebuild();
files.clear();
result.outputFiles.forEach(f => files.set(`/${path.relative(devDir, f.path).replace(/\\/g, '/')}`, f.contents));
console.log(`[client] built in ${((Date.now() - start) / 1000).toFixed(1)}s`);
reloadClients.forEach(res => res.write('data: reload\n\n'));
}
catch {
console.log(`[client] build failed in ${((Date.now() - start) / 1000).toFixed(1)}s, waiting for changes`);
}
});
return building;
};
await rebuild();
let pending = new Set();
let timeout;
const onChange = dir => (_event, fileName) => {
if (!fileName || /(^|[\\/])\./.test(fileName)) {
return;
}
pending.add(path.join(dir, fileName));
clearTimeout(timeout);
timeout = setTimeout(() => {
const changed = [...pending];
pending = new Set();
rebuild(changed);
}, 50);
};
for (const dir of [path.join(root, 'src', 'ts'), path.join(root, 'src', 'styles')]) {
fs.watch(dir, { recursive: true }, onChange(dir));
}
const types = { '.js': 'application/javascript', '.map': 'application/json', '.css': 'text/css' };
http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost').pathname;
const headers = { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-cache' };
if (url === '/reload') {
res.writeHead(200, { ...headers, 'Content-Type': 'text/event-stream' });
res.write('\n');
reloadClients.add(res);
req.on('close', () => reloadClients.delete(res));
return;
}
await building;
const contents = files.get(url);
if (contents) {
res.writeHead(200, { ...headers, 'Content-Type': types[path.extname(url)] || 'application/octet-stream' });
res.end(contents);
}
else {
res.writeHead(404, headers);
res.end();
}
}).listen(DEV_PORT, '0.0.0.0', () => console.log(`[client] dev server on http://localhost:${DEV_PORT}/assets/scripts/`));
}
if (dev) {
await runDev();
}
else {
const start = Date.now();
try {
await Promise.all(selectBundles().map(buildProd));
console.log(`[client] done in ${((Date.now() - start) / 1000).toFixed(1)}s`);
}
catch (e) {
if (!e.errors) {
console.error(e);
}
process.exit(1);
}
}
+6 -25
View File
@@ -52,7 +52,7 @@ function swallowError(e) {
const runAsync = (command, args) => new Promise((resolve, reject) => {
const proc = spawn(command, args)
.on('error', reject)
.on('exit', resolve);
.on('exit', code => code ? reject(new Error(`${command} ${args.join(' ')} exited with code ${code}`)) : resolve());
proc.stdout.pipe(process.stdout);
proc.stderr.pipe(process.stderr);
@@ -354,26 +354,9 @@ const patchWebWorkerTask = cb => {
cb();
};
const webpackScript = argv.debug ? 'webpack-debug' : 'webpack-prod';
const webpackArgs = ['--'];
if (argv.beta) {
webpackArgs.push('--env', 'beta');
}
if (argv.timing) {
webpackArgs.push('--env', 'timing');
}
// each bundle is built in its own webpack process, webpack builds multiple configs
// in a single process one after another, so this makes use of multiple cores
const webpackBundles = argv.main ? ['bootstrap'] : ['bootstrap', 'bootstrap-admin', 'bootstrap-tools'];
const webpackProd = gulp.parallel(...webpackBundles.map(bundle => {
const task = npmScript(webpackScript, [...webpackArgs, '--env', `bundle=${bundle}`]);
task.displayName = `webpack (${bundle})`;
return task;
}));
const webpackAdmin = npmScript('webpack-admin');
const clientArgs = ['--', ...['debug', 'beta', 'timing', 'main'].filter(arg => argv[arg]).map(arg => `--${arg}`)];
const clientProd = npmScript('client', clientArgs);
const clientAdmin = npmScript('client-admin');
const sw = npmScript('sw');
const assets = gulp.series(assetsCopy, assetsRev);
@@ -426,13 +409,11 @@ const empty = cb => cb();
const spritesTask = argv.sprites ? sprites : empty;
//const buildSprites = gulp.series(tsTools, sprites);
// tsc and webpack depend on generated files (codegen + rev.ts from assets), sass does not,
// so sass runs alongside them. webpack is the long pole. sw + size must wait for all of them.
const build = gulp.series(clean, setProd, gulp.parallel(
gulp.series(gulp.parallel(codegen, assets), gulp.parallel(ts, webpackProd)),
gulp.series(gulp.parallel(codegen, assets), gulp.parallel(ts, clientProd)),
sassTasks,
), sw, size);
const admin = gulp.series(cleanAdmin, setProd, sassAdmin, ts, webpackAdmin);
const admin = gulp.series(cleanAdmin, setProd, sassAdmin, ts, clientAdmin);
const dev = gulp.series(clean, spritesTask, common, gulp.parallel(serverDev, watch, watchTools));
export {
+239 -7473
View File
File diff suppressed because it is too large. Load diff
+9 -28
View File
@@ -18,14 +18,13 @@
"ts-watch": "npm run ts -- --watch",
"ts-cov": "npm run ts -- --target es5",
"ts-cov-watch": "npm run ts -- --target es5 --watch",
"webpack-prod": "node --max_old_space_size=8192 node_modules/webpack-cli/bin/cli --config webpack.prod.mjs --progress --color",
"webpack-main": "npm run webpack-prod -- --env main",
"webpack-analyze": "npm run webpack-prod -- --env analyze",
"webpack-debug": "npm run webpack-prod -- --env debug",
"webpack-admin": "npm run webpack-prod -- --env admin",
"webpack-stats": "npm run webpack-prod -- --env debug --json > stats.json",
"webpack-verbose": "npm run webpack-prod -- --verbose",
"wds": "webpack-dev-server --config webpack.dev.mjs --progress --color --port 8091",
"client": "node --require ./tools/angular-pug-hook.cjs build-client.mjs",
"client-main": "npm run client -- --main",
"client-analyze": "npm run client -- --analyze",
"client-debug": "npm run client -- --debug",
"client-admin": "npm run client -- --admin",
"wds": "node build-client.mjs --dev",
"wds-aot": "npm run client -- --dev --aot",
"clean": "gulp clean",
"build": "gulp build",
"build-sprites": "npm run ts-tools && gulp sprites && npm run build",
@@ -46,8 +45,8 @@
"update-fontawesome": "npm update @fortawesome/fontawesome-svg-core @fortawesome/free-brands-svg-icons @fortawesome/free-solid-svg-icons @fortawesome/angular-fontawesome --save"
},
"devDependencies": {
"@angular-devkit/build-angular": "22.1.2",
"@angular/animations": "22.1.0",
"@angular/build": "22.1.2",
"@angular/common": "22.1.0",
"@angular/compiler": "22.1.0",
"@angular/compiler-cli": "22.1.0",
@@ -61,7 +60,7 @@
"@fortawesome/fontawesome-svg-core": "6.7.2",
"@fortawesome/free-brands-svg-icons": "6.7.2",
"@fortawesome/free-solid-svg-icons": "6.7.2",
"@ngtools/webpack": "22.1.2",
"@jridgewell/remapping": "2.3.5",
"@rollup/plugin-babel": "6.1.0",
"@swc/core": "^1.15.47",
"@types/bluebird": "3.5.42",
@@ -96,15 +95,12 @@
"@types/yargs": "17.0.35",
"@typescript-eslint/eslint-plugin": "8.57.1",
"@typescript-eslint/parser": "8.57.1",
"angular2-template-loader": "0.6.2",
"babel-loader": "10.1.1",
"c8": "^12.0.0",
"chai": "6.2.2",
"chai-as-promised": "8.0.2",
"chalk": "5.6.2",
"del": "8.0.1",
"esbuild": "^0.28.1",
"esbuild-loader": "^4.5.0",
"eslint": "8.57.1",
"eslint-config-google": "0.14.0",
"eslint-config-standard": "17.1.0",
@@ -112,7 +108,6 @@
"eslint-plugin-node": "11.1.0",
"eslint-plugin-promise": "6.1.1",
"focus-visible": "5.0.2",
"fork-ts-checker-webpack-plugin": "^9.1.0",
"gulp": "5.0.1",
"gulp-autoprefixer": "10.0.0",
"gulp-cssnano": "2.1.3",
@@ -133,22 +128,13 @@
"reflect-metadata": "0.2.2",
"rxjs": "7.8.2",
"sass-embedded": "1.108.2",
"sass-loader": "17.1.1",
"sinon": "21.0.3",
"swc-loader": "^0.2.7",
"ts-loader": "9.5.4",
"ts-node": "10.9.2",
"tslib": "2.8.1",
"tsutils": "3.17.1",
"typescript": "6.0.3",
"typescript-7": "npm:[email protected]",
"webpack": "5.105.4",
"webpack-bundle-analyzer": "5.2.0",
"webpack-cli": "7.0.2",
"webpack-dev-server": "5.2.3",
"webpack-merge": "6.0.1",
"workbox-cli": "7.4.0",
"wrapper-webpack-plugin": "2.2.2",
"zone.js": "0.15.1"
},
"dependencies": {
@@ -195,15 +181,10 @@
"passport-tumblr": "0.1.2",
"passport-twitter": "1.0.4",
"passport-vkontakte": "0.3.2",
"postcss": "8.5.8",
"postcss-loader": "8.2.1",
"pug": "3.0.4",
"pug-html-loader": "1.1.7",
"pug-plugin-ng": "0.0.3",
"raw-loader": "4.0.2",
"rollbar": "2.12.2",
"serve-favicon": "2.5.0",
"source-list-map": "2.0.1",
"source-map-support": "0.5.13",
"timsort": "0.3.0",
"tracer": "1.0.1",
-28
View File
@@ -1,28 +0,0 @@
import { transformAsync } from '@babel/core';
import linkerPlugin from '@angular/compiler-cli/linker/babel';
import { needsLinking } from '@angular/compiler-cli/linker';
export default function angularLinkerLoader(content, map) {
const callback = this.async();
(async () => {
try {
const filename = this.resourcePath;
if (!needsLinking(filename, content)) {
callback(null, content, map);
return;
}
// Create a fresh plugin instance per file. The linker plugin is stateful
// and cannot be shared across concurrent transforms.
const { code, map: resultMap } = await transformAsync(content, {
filename,
sourceFileName: filename,
sourceMaps: !!this.sourceMap,
compact: false,
plugins: [api => linkerPlugin(api, { sourceMapping: false })],
});
callback(null, code, resultMap || undefined);
} catch (err) {
callback(err);
}
})();
}
+16
View File
@@ -0,0 +1,16 @@
const path = require('path');
const { compilePugTemplate } = require('./pug-template.cjs');
const angularHost = require(path.join(__dirname, '..', 'node_modules', '@angular', 'build', 'src', 'tools', 'angular', 'angular-host.js'));
const createAngularCompilerHost = angularHost.createAngularCompilerHost;
angularHost.createAngularCompilerHost = function (...args) {
const host = createAngularCompilerHost.apply(this, args);
const readResource = host.readResource;
host.readResource = async function (fileName) {
return fileName.endsWith('.pug') ? compilePugTemplate(fileName) : readResource.call(this, fileName);
};
return host;
};
global.angularPugHook = true;
+14
View File
@@ -0,0 +1,14 @@
const fs = require('fs');
const pug = require('pug');
const pugPluginNg = require('pug-plugin-ng');
function compilePugTemplate(file) {
return pug.compile(fs.readFileSync(file, 'utf8'), {
filename: file,
doctype: 'html',
compileDebug: false,
plugins: [pugPluginNg],
})({});
}
module.exports = { compilePugTemplate };
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig-aot.json",
"files": [
"src/ts/bootstrap.ts",
"src/ts/bootstrap-admin.ts",
"src/ts/bootstrap-tools.ts"
]
}
-1
View File
@@ -76,5 +76,4 @@ html(lang="en")
if production
script(src=script async)
else
script(src="http://" + address + ":"+ port + "/assets/scripts/vendor.js")
script(src="http://" + address + ":"+ port + script.replace('/adm/', '/'))
-128
View File
@@ -1,128 +0,0 @@
import webpack from 'webpack';
import path from 'path';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import { fileURLToPath } from 'url';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const config = {
context: path.join(__dirname, 'src'),
output: {
path: path.resolve(__dirname, 'dist', 'assets', 'scripts'),
filename: '[name].js',
publicPath: '/assets/scripts/',
},
resolve: {
extensions: ['.ts', '.js'],
fallback: {
util: require.resolve('util/'),
},
},
module: {
rules: [
{
test: /\.js$/,
use: ['angular2-template-loader'],
exclude: [/node_modules/],
},
{
test: /\.css$/,
use: [
{
loader: 'raw-loader',
options: {
esModule: false,
},
},
],
},
{
test: /\.html$/,
use: [
{
loader: 'raw-loader',
options: {
esModule: false,
},
},
],
},
{
test: /\.pug$/,
use: [
{
loader: 'raw-loader',
options: {
esModule: false,
},
},
{
loader: 'pug-html-loader',
options: {
doctype: 'html',
plugins: (await import('pug-plugin-ng')).default,
},
},
],
},
{
test: /\.scss$/,
use: [
{
loader: 'raw-loader',
options: {
esModule: false,
},
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
ident: 'postcss',
plugins: [
autoprefixer('last 2 versions'),
cssnano({
discardComments: {
removeAll: true,
},
}),
],
},
},
},
{
loader: 'sass-loader',
options: {
api: 'modern',
sassOptions: {
loadPaths: ['src/styles'],
quietDeps: true,
silenceDeprecations: ['import', 'global-builtin', 'color-functions', 'if-function', 'slash-div'],
},
},
},
],
},
{
test: /[\\/\\]@angular[\\/\\]core[\\/\\].+\.js$/,
parser: {
system: false,
},
},
],
},
plugins: [
new webpack.ContextReplacementPlugin(
/\\@angular(\\|\/)core(\\|\/)/,
path.resolve(__dirname, 'src', 'ts'),
{}
),
],
};
export default config;
-132
View File
@@ -1,132 +0,0 @@
import webpack from 'webpack';
import { merge } from 'webpack-merge';
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
import common from './webpack.common.mjs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const config = merge(common, {
mode: 'development',
entry: {
bootstrap: './ts/bootstrap',
'bootstrap-admin': './ts/bootstrap-admin',
'bootstrap-tools': './ts/bootstrap-tools',
},
devtool: 'eval-cheap-source-map',
ignoreWarnings: [/was not found/],
devServer: {
host: '0.0.0.0',
port: 8091,
historyApiFallback: true,
compress: false,
client: {
progress: true,
overlay: {
errors: true,
warnings: false,
},
},
static: {
publicPath: '/assets/scripts/',
},
allowedHosts: 'all',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers':
'X-Requested-With, content-type, Authorization',
},
},
stats: {
preset: 'normal',
reasons: true,
modules: true,
errorDetails: true,
moduleTrace: true,
},
cache: {
type: 'filesystem',
cacheDirectory: path.resolve(__dirname, '.cache', 'webpack', 'dev'),
buildDependencies: {
config: [fileURLToPath(import.meta.url), path.resolve(__dirname, 'webpack.common.mjs')],
},
},
output: {
pathinfo: false,
},
watchOptions: {
ignored: /node_modules/,
},
module: {
rules: [
{
test: /\.ts$/,
use: [
{
loader: 'swc-loader',
options: {
jsc: {
parser: {
syntax: 'typescript',
decorators: true,
},
transform: {
legacyDecorator: true,
decoratorMetadata: true,
useDefineForClassFields: false,
},
target: 'es6',
},
module: {
type: 'es6',
},
sourceMaps: true,
},
},
'angular2-template-loader',
],
},
],
},
optimization: {
removeAvailableModules: false,
removeEmptyChunks: false,
moduleIds: 'named',
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all',
},
},
},
},
plugins: [
new ForkTsCheckerWebpackPlugin({
async: true,
typescript: {
configFile: path.resolve(__dirname, 'tsconfig.json'),
configOverwrite: {
compilerOptions: {
target: 'es6',
module: 'es6',
},
},
memoryLimit: 4096,
},
}),
new webpack.DefinePlugin({
DEVELOPMENT: true,
TOOLS: true,
SERVER: false,
BETA: true,
TIMING: true,
TESTS: false,
}),
],
});
export default config;
-175
View File
@@ -1,175 +0,0 @@
import path from 'path';
import webpack from 'webpack';
import { merge } from 'webpack-merge';
import TerserPlugin from 'terser-webpack-plugin';
import { EsbuildPlugin } from 'esbuild-loader';
import WrapperPlugin from 'wrapper-webpack-plugin';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import { AngularWebpackPlugin } from '@ngtools/webpack';
import common from './webpack.common.mjs';
import fs from 'fs';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const r = p => JSON.parse(fs.readFileSync(p, 'utf8'));
const config = r('./config.json');
const analytics = config.analytics ? `
(function(i, s, o, g, r, a, m) {i['GoogleAnalyticsObject']=r; i[r]=i[r]||function() {
(i[r].q=i[r].q||[]).push(arguments) }, i[r].l=1*new Date(); a=s.createElement(o),
m=s.getElementsByTagName(o)[0]; a.async=1; a.src=g; m.parentNode.insertBefore(a, m)
}) (window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', '${config.analytics.trackingID}', 'auto');
ga('send', 'pageview');
` : ``;
const compilerOptions = r('./tsconfig-aot.json').compilerOptions;
//const compilerOptionsES = r('./tsconfig-aot-es.json').compilerOptions;
const scripts = [
['bootstrap', 'app/app.module#AppModule', 'assets', compilerOptions, 'tsconfig-aot.json', 5, false],
// ['bootstrap-es', 'app/app.module#AppModule', 'assets', compilerOptionsES, 'tsconfig-aot-es.json', 7, false],
['bootstrap-admin', 'admin/admin.module#AdminAppModule', 'assets-admin', compilerOptions, 'tsconfig-aot-admin.json', 5, true],
['bootstrap-tools', 'tools/tools.module#ToolsAppModule', 'assets', compilerOptions, 'tsconfig-aot-tools.json', 5, true],
];
const max = Math.max(...([...scripts].map(e => e[0].length)));
function getScripts(args) {
const { analyze, main, admin, tools, beta, bundle } = args;
if (bundle) {
const found = scripts.filter(s => s[0] === bundle);
if (!found.length) {
throw new Error(`Unknown bundle: ${bundle}`);
}
return found;
}
if (tools || beta) {
return [...scripts];
}
if (analyze || main) {
return [scripts[0]];
} else if (admin) {
return [scripts[1]];
} else {
return scripts;
}
}
export default (args = {}) =>
getScripts(args)
.map(([script, entry, outDir, compilerOptions, tsconfig, _ecma, TOOLS]) => {
const minimizer = args.debug ? [
// Fast iteration: esbuild minify is ~40x faster than Terser,
// at the cost of ~11% larger bundles.
new EsbuildPlugin({
target: 'es2022',
legalComments: 'external',
}),
] : [
new TerserPlugin({
minify: TerserPlugin.swcMinify,
extractComments: {
condition: true,
banner: false,
},
terserOptions: {
ecma: 5,
mangle: {
// swc regex has no lookahead, so '__default' is kept through reserved list
props: {
regex: '^__',
reserved: ['__default'],
},
},
format: { comments: false },
},
}),
];
return merge(common, {
mode: 'production',
performance: {
maxEntrypointSize: 10000000,
maxAssetSize: 10000000,
},
entry: {
[script]: `./ts/${script}`,
},
output: Object.assign({}, common.output, {
filename: '[name]-[chunkhash:10].js',
path: path.resolve(__dirname, 'dist', 'browser' , outDir, 'scripts'),
}),
devtool: script === 'bootstrap' ? 'source-map' : false,
cache: {
type: 'filesystem',
name: script,
cacheDirectory: path.resolve(__dirname, '.cache', 'webpack', 'prod'),
buildDependencies: {
config: [
fileURLToPath(import.meta.url),
path.resolve(__dirname, 'webpack.common.mjs'),
path.resolve(__dirname, tsconfig),
path.resolve(__dirname, 'tools/angular-linker-loader.mjs'),
],
},
},
module: {
rules: [
{
test: /\.m?js$/,
use: {
loader: path.resolve(__dirname, 'tools/angular-linker-loader.mjs'),
},
},
{
test: /\.[jt]sx?$/,
use: [{
loader: '@ngtools/webpack', options: {
sourcemap: true,
compilerOptions,
}
}],
},
],
},
stats: {
preset: 'normal',
reasons: true,
modules: true,
errorDetails: true,
moduleTrace: true
},
optimization: {
minimizer,
},
plugins: [
new AngularWebpackPlugin({
tsconfig,
}),
(script === 'bootstrap' && !args.analyze) ? new WrapperPlugin({ test: /\.js$/, header: analytics }) : undefined,
args.analyze ? new BundleAnalyzerPlugin({ analyzerMode: 'static' }) : undefined,
new webpack.DefinePlugin({
DEVELOPMENT: false, TOOLS, SERVER: false, BETA: !!args.beta,
TIMING: !!args.timing, TESTS: false,
ngJitMode: false, // NOTE: Enable this if you need more detailed JIT compiler error
ngI18nClosureMode: false, // disables localization closure
ngDevMode: false, // Disable angular dev
}),
new webpack.IgnorePlugin({ resourceRegExp: /^\.\/locale$/, contextRegExp: /moment$/ }),
new webpack.ProgressPlugin({
handler: (percentage, message, ...args) => {
const fullMsg = `${args.join(' ')} ${message}`.trim();
const p = Math.floor(percentage * 100).toString();
const emp = ' '.repeat(3 - p.length);
const l = script.length;
const emp2 = ' '.repeat(max - l);
console.log(`[${p}%]${emp}[${script}] ${emp2} | ${fullMsg}`);
},
}),
].filter(x => x),
});
});