2023-07-27 15:24:49 +00:00
|
|
|
import fs from "node:fs/promises";
|
|
|
|
import path from "node:path";
|
|
|
|
import UglifyJS from "uglify-js";
|
|
|
|
import processForDist from "./dist.js";
|
|
|
|
import getTimestamp from "./lib/getTimestamp.js";
|
2023-09-20 22:18:42 +00:00
|
|
|
|
|
|
|
const rjs = /\.js$/;
|
|
|
|
|
2023-07-27 15:24:49 +00:00
|
|
|
export default async function minify( { dir, filename } ) {
|
2023-09-20 22:18:42 +00:00
|
|
|
const filepath = path.join( dir, filename );
|
2024-03-10 16:19:15 +00:00
|
|
|
const contents = await fs.readFile( filepath, "utf8" );
|
2023-09-20 22:18:42 +00:00
|
|
|
const version = /jQuery JavaScript Library ([^\n]+)/.exec( contents )[ 1 ];
|
2023-11-01 23:48:05 +00:00
|
|
|
const banner = `/*! jQuery ${ version }` +
|
2023-09-20 22:18:42 +00:00
|
|
|
" | (c) OpenJS Foundation and other contributors" +
|
|
|
|
" | jquery.org/license */";
|
|
|
|
|
|
|
|
const minFilename = filename.replace( rjs, ".min.js" );
|
|
|
|
const mapFilename = filename.replace( rjs, ".min.map" );
|
|
|
|
|
|
|
|
const { code, error, map: incompleteMap, warning } = UglifyJS.minify(
|
|
|
|
contents,
|
|
|
|
{
|
|
|
|
compress: {
|
|
|
|
hoist_funs: false,
|
|
|
|
loops: false,
|
|
|
|
|
|
|
|
// Support: IE <11
|
|
|
|
// typeofs transformation is unsafe for IE9-10
|
|
|
|
// See https://github.com/mishoo/UglifyJS2/issues/2198
|
|
|
|
typeofs: false
|
|
|
|
},
|
|
|
|
output: {
|
|
|
|
ascii_only: true,
|
|
|
|
|
|
|
|
// Support: Android 4.0 only
|
|
|
|
// UglifyJS 3 breaks Android 4.0 if this option is not enabled.
|
|
|
|
// This is in lieu of setting ie for all of mangle, compress, and output
|
|
|
|
ie8: true,
|
|
|
|
preamble: banner
|
|
|
|
},
|
|
|
|
sourceMap: {
|
|
|
|
filename: minFilename
|
|
|
|
}
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
if ( error ) {
|
|
|
|
throw new Error( error );
|
|
|
|
}
|
|
|
|
|
|
|
|
if ( warning ) {
|
|
|
|
console.warn( warning );
|
|
|
|
}
|
|
|
|
|
|
|
|
// The map's `sources` property is set to an array index.
|
|
|
|
// Fix it by setting it to the correct filename.
|
|
|
|
const map = JSON.stringify( {
|
|
|
|
...JSON.parse( incompleteMap ),
|
|
|
|
file: minFilename,
|
|
|
|
sources: [ filename ]
|
|
|
|
} );
|
|
|
|
|
|
|
|
await Promise.all( [
|
2024-03-10 16:19:15 +00:00
|
|
|
fs.writeFile(
|
2023-09-20 22:18:42 +00:00
|
|
|
path.join( dir, minFilename ),
|
|
|
|
code
|
|
|
|
),
|
2024-03-10 16:19:15 +00:00
|
|
|
fs.writeFile(
|
2023-09-20 22:18:42 +00:00
|
|
|
path.join( dir, mapFilename ),
|
|
|
|
map
|
|
|
|
)
|
|
|
|
] );
|
|
|
|
|
|
|
|
// Always process files for dist
|
|
|
|
// Doing it here avoids extra file reads
|
|
|
|
processForDist( contents, filename );
|
|
|
|
processForDist( code, minFilename );
|
|
|
|
processForDist( map, mapFilename );
|
|
|
|
|
2023-11-01 23:48:05 +00:00
|
|
|
console.log( `[${ getTimestamp() }] ${ minFilename } ${ version } with ${
|
|
|
|
mapFilename
|
|
|
|
} created.` );
|
2023-07-27 15:24:49 +00:00
|
|
|
}
|