This repository has been archived by the owner on Mar 15, 2020. It is now read-only.
/
index.js
63 lines (52 loc) · 1.73 KB
/
index.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
import minifyPreset from 'babel-preset-minify';
import bannerPlugin from '@comandeer/babel-plugin-banner';
import { getCommentContent } from '@comandeer/babel-plugin-banner';
import { transform } from '@babel/core';
import { filterMinifyOptions } from './utils.js';
import { addNewLine } from './utils.js';
import { isFn } from './utils.js';
import { isFnOrString } from './utils.js';
function minify( options = {} ) {
return {
name: 'babel-minify',
renderChunk( bundle, chunkInfo, { banner: bundleBanner } ) {
const minifyOptions = filterMinifyOptions( options );
const babelConf = {
presets: [ [ minifyPreset, minifyOptions ] ],
sourceMaps: typeof options.sourceMap !== 'undefined' ? Boolean( options.sourceMap ) : true,
comments: typeof options.comments !== 'undefined' ? Boolean( options.comments ) : true,
plugins: Array.isArray( options.plugins ) ? options.plugins : []
};
let banner;
if ( isFnOrString( options.banner ) || isFnOrString ( bundleBanner ) ) {
banner = options.banner || bundleBanner;
banner = isFn ( banner ) ? banner() : banner;
const bannerContent = getCommentContent( banner );
let isAlreadyInserted = false;
babelConf.plugins = babelConf.plugins.concat( [
[ bannerPlugin, {
banner
} ]
] );
if ( !babelConf.comments ) {
babelConf.shouldPrintComment = ( comment ) => {
if ( !isAlreadyInserted && comment === bannerContent ) {
isAlreadyInserted = true;
return true;
}
return false;
};
}
}
let { code, map } = transform( bundle, babelConf );
if ( options.bannerNewLine ) {
( { code, map } = addNewLine( code, map, banner ) );
}
return {
code,
map
};
}
};
}
export default minify;