11const path = require ( "path" ) ;
22const chalk = require ( "chalk" ) ;
3+ const fs = require ( "fs" ) ;
34const fg = require ( "fast-glob" ) ;
5+ const getDirName = path . dirname ;
46
57function detectDeadCode ( compilation , options ) {
68 const isWebpack5 = compilation . chunkGraph ? true : false ;
@@ -13,27 +15,60 @@ function detectDeadCode(compilation, options) {
1315
1416 if ( options . detectUnusedFiles ) {
1517 unusedFiles = includedFiles . filter ( file => ! compiledFiles [ file ] ) ;
16-
17- if ( Object . keys ( unusedFiles ) . length > 0 || options . log === "all" ) {
18+ if ( ( Object . keys ( unusedFiles ) . length > 0 && options . log !== "none" ) || options . log === "all" ) {
1819 logUnusedFiles ( unusedFiles ) ;
1920 }
2021 }
2122
2223 if ( options . detectUnusedExport ) {
2324 unusedExportMap = getUsedExportMap ( convertFilesToDict ( includedFiles ) , compilation , isWebpack5 ) ;
2425
25- if ( Object . keys ( unusedExportMap ) . length > 0 || options . log == "all" ) {
26+ if ( ( Object . keys ( unusedExportMap ) . length > 0 && options . log !== "none" ) || options . log = == "all" ) {
2627 logUnusedExportMap ( unusedExportMap ) ;
2728 }
2829 }
2930
31+ if ( options . exportJSON ) {
32+ let exportPath = "deadcode.json" ;
33+ if ( typeof options . exportJSON === "string" ) {
34+ exportPath = options . exportJSON + "/" + exportPath ;
35+ }
36+ try {
37+ fs . stat ( exportPath , err => {
38+ if ( err == null ) {
39+ fs . unlinkSync ( exportPath ) ;
40+ return exportResultToJSON ( exportPath , unusedFiles , unusedExportMap ) ;
41+ }
42+ if ( err . code === "ENOENT" ) {
43+ return exportResultToJSON ( exportPath , unusedFiles , unusedExportMap ) ;
44+ }
45+ } ) ;
46+ } catch ( error ) {
47+ console . error ( "export result to json error: " , error ) ;
48+ }
49+ }
50+
3051 if ( unusedFiles . length > 0 || unusedExportMap . length > 0 ) {
3152 if ( options . failOnHint ) {
3253 process . exit ( 2 ) ;
3354 }
3455 }
3556}
3657
58+ function exportResultToJSON ( exportPath , unusedFiles , unusedExports ) {
59+ const data = {
60+ unusedFiles,
61+ unusedExports,
62+ } ;
63+ fs . mkdir ( getDirName ( exportPath ) , { recursive : true } , err => {
64+ if ( err ) throw err ;
65+ fs . writeFile ( exportPath , JSON . stringify ( data , null , 2 ) , err => {
66+ if ( err ) throw err ;
67+ console . info ( path . resolve ( exportPath ) + " is generated." ) ;
68+ } ) ;
69+ } ) ;
70+ }
71+
3772function getPattern ( { context, patterns, exclude } ) {
3873 return patterns
3974 . map ( pattern => path . resolve ( context , pattern ) )
0 commit comments