|
| 1 | +import type { IApi } from '@kmijs/types' |
| 2 | + |
| 3 | +export default (api: IApi) => { |
| 4 | + api.describe({ |
| 5 | + key: 'removeConsole', |
| 6 | + config: { |
| 7 | + schema({ zod }) { |
| 8 | + return zod.union([ |
| 9 | + zod.boolean(), |
| 10 | + zod.array(zod.enum(['error', 'warn', 'info', 'log'])), |
| 11 | + ]) |
| 12 | + }, |
| 13 | + }, |
| 14 | + enableBy: api.EnableBy.config, |
| 15 | + }) |
| 16 | + |
| 17 | + api.onCheckConfig(({ userConfig }) => { |
| 18 | + if (userConfig.jsMinifier === 'uglifyJs') { |
| 19 | + throw new Error('removeConsole does not support uglifyJs') |
| 20 | + } |
| 21 | + if (api.appData.bundler === 'webpack' && userConfig.jsMinifier === 'swc') { |
| 22 | + throw new Error('removeConsole does not support using swc compression in webpack mode') |
| 23 | + } |
| 24 | + }) |
| 25 | + |
| 26 | + api.modifyConfig((memo) => { |
| 27 | + const { removeConsole } = memo |
| 28 | + const isRspack = api.appData.bundler === 'rspack' |
| 29 | + // Default is esbuild |
| 30 | + const jsMinifier = |
| 31 | + api.appData.bundler === 'rspack' |
| 32 | + ? api.userConfig.jsMinifier || 'swc' |
| 33 | + : api.userConfig.jsMinifier || 'esbuild' |
| 34 | + |
| 35 | + const compressOptions = Array.isArray(removeConsole) |
| 36 | + ? { pure_funcs: removeConsole.map((method) => `console.${method}`) } |
| 37 | + : { drop_console: true } |
| 38 | + |
| 39 | + if (isRspack && jsMinifier === 'swc') { |
| 40 | + memo.jsMinifierOptions = { |
| 41 | + ...memo.jsMinifierOptions, |
| 42 | + minimizerOptions: { |
| 43 | + ...memo.jsMinifierOptions?.minimizerOptions, |
| 44 | + compress: { |
| 45 | + ...memo.jsMinifierOptions?.minimizerOptions?.compress, |
| 46 | + ...compressOptions, |
| 47 | + }, |
| 48 | + }, |
| 49 | + } |
| 50 | + return memo |
| 51 | + } |
| 52 | + |
| 53 | + // esbuild |
| 54 | + if (jsMinifier === 'esbuild') { |
| 55 | + const compressOptions = Array.isArray(removeConsole) |
| 56 | + ? { pure: removeConsole.map((method) => `console.${method}`) } |
| 57 | + : { drop: ['console'] } |
| 58 | + memo.jsMinifierOptions = { |
| 59 | + ...memo.jsMinifierOptions, |
| 60 | + ...compressOptions, |
| 61 | + } |
| 62 | + return memo |
| 63 | + } |
| 64 | + |
| 65 | + // terser |
| 66 | + if (jsMinifier === 'terser') { |
| 67 | + memo.jsMinifierOptions = { |
| 68 | + ...memo.jsMinifierOptions, |
| 69 | + compress: { |
| 70 | + ...memo.jsMinifierOptions?.compress, |
| 71 | + ...compressOptions, |
| 72 | + }, |
| 73 | + } |
| 74 | + return memo |
| 75 | + } |
| 76 | + return memo |
| 77 | + }) |
| 78 | +} |
0 commit comments