aboutsummaryrefslogtreecommitdiffstats
path: root/build/tasks/minify.js
blob: 6d3c6c568b758d338a7e1c8a482ad0aad04cc5ec (plain)
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
/**
 * Minify JavaScript using SWC.
 */

"use strict";

module.exports = ( grunt ) => {
	const swc = require( "@swc/core" );

	grunt.registerMultiTask(
		"minify",
		"Minify JavaScript using SWC",
		async function() {
			const done = this.async();
			const options = this.options();
			const sourceMapFilename = options.sourceMap && options.sourceMap.filename;
			const sourceMapOverrides = options.sourceMap && options.sourceMap.overrides || {};

			await Promise.all( this.files.map( async( { src, dest } ) => {
				if ( src.length !== 1 ) {
					grunt.fatal( "The minify task requires a single source per destination" );
				}

				const { code, map: incompleteMap } = await swc.minify(
					grunt.file.read( src[ 0 ] ),
					{
						...options.swc,
						inlineSourcesContent: false,
						sourceMap: sourceMapFilename ?
							{
								filename: sourceMapFilename
							} :
							false
					}
				);

				// Can't seem to get SWC to not use CRLF on Windows, so replace them with LF.
				grunt.file.write( dest, code.replace( /\r\n/g, "\n" ) );

				if ( sourceMapFilename ) {

					// Apply map overrides if needed. See the task config description
					// for more details.
					const mapObject = {
						...JSON.parse( incompleteMap ),
						...sourceMapOverrides
					};
					const map = JSON.stringify( mapObject );

					grunt.file.write( sourceMapFilename, map );
				}
			} ) );

			done();
		}
	);
};