-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.ts
149 lines (141 loc) · 5.11 KB
/
index.ts
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import path from 'path';
import fs from 'fs-extra';
import { Configuration } from 'webpack';
import CssMinimizerPlugin, { BasePluginOptions, DefinedDefaultMinimizerAndOptions } from 'css-minimizer-webpack-plugin';
import { overridePaths, Paths, LoaderConfOptions, MiniCssExtractPlugin } from 'kkt';
import './overridesCheckRequiredFiles';
import { checkRequiredFiles } from './checkRequiredFiles';
import TerserPlugin, {
DefinedDefaultMinimizerAndOptions as TerserPluginDefinedDefaultMinimizerAndOptions,
} from 'terser-webpack-plugin';
export type ReactLibraryOptions = LoaderConfOptions & {
bundle?: boolean;
mini?: boolean;
name?: string;
module?: string;
isNotCheckHTML?: boolean;
overridePaths?: Partial<Paths>;
main: string;
outputDir?: string;
dependencies?: Configuration['externals'];
cssMinimizerPluginOptions?: BasePluginOptions & DefinedDefaultMinimizerAndOptions<any>;
miniCssExtractPluginOptions?: MiniCssExtractPlugin.PluginOptions;
terserPluginOptions?: BasePluginOptions & TerserPluginDefinedDefaultMinimizerAndOptions<any>;
};
/** Output Dir */
let outputDir = path.join(process.cwd(), 'dist');
let buildCacheDir = '';
let fileName = '';
let publicPath = '';
process.on('beforeExit', () => {
fs.ensureDirSync(outputDir);
if (buildCacheDir) {
console.log(`Output Dir: \x1b[32m${outputDir}\x1b[0m.`);
console.log(` ╰┬┈┈┈┈▷ The \x1b[32m${outputDir.replace(process.cwd(), '')}\x1b[0m folder is ready.`);
const dirs = (fs.readdirSync(buildCacheDir, {}) as string[]).filter((name: any) =>
new RegExp(`^${fileName}\.`).test(name),
);
dirs.forEach((name, idx) => {
console.log(` ${dirs.length === idx + 1 ? '╰' : '├'}┈ File: \x1b[32m${name}\x1b[0m.`);
fs.copyFileSync(path.join(buildCacheDir, name), path.join(outputDir, name));
});
}
if (publicPath) {
fs.removeSync(publicPath);
}
});
export default (conf: Configuration, env: string, options = {} as ReactLibraryOptions): Configuration => {
const { isNotCheckHTML = false } = options;
if (!conf) {
throw Error('KKT:ConfigPaths: there is no config file found');
}
if (!options.main) {
throw Error('KKT:ConfigPaths: main Required option.');
}
if (!options.bundle && options.paths) {
/**
* Remove validation first, then add validation
* Warn and crash if required files are missing
*/
if (!checkRequiredFiles([options.paths.appHtml, options.paths.appIndexJs], isNotCheckHTML)) {
process.exit(1);
}
}
if (options.bundle) {
if (options.paths && options.paths.appPath) {
publicPath = path.join(options.paths.appPath, 'public');
if (fs.existsSync(publicPath)) {
publicPath = '';
} else {
fs.ensureDirSync(publicPath);
}
}
outputDir = options.outputDir || outputDir;
buildCacheDir = path.join(process.cwd(), 'node_modules', '.cache', 'kkt', options.mini ? '.~lib.min' : '.~lib');
/** 确保缓存目录存在 */
fs.ensureDirSync(buildCacheDir);
overridePaths(undefined, { appBuild: buildCacheDir, ...options.overridePaths });
const libraryName = path.basename(options.name || '');
const entryFile = options.module;
const outFile = path.basename(options.main);
let minfilename = outFile.split('.');
fileName = minfilename[0] || libraryName;
minfilename.splice(1, 0, 'min');
if (entryFile) {
conf.entry = path.resolve(entryFile);
}
conf.devtool = false;
conf.output = {
// commonjs
libraryTarget: 'umd',
filename: outFile,
path: buildCacheDir,
};
if (libraryName) {
conf.output.library = libraryName;
}
conf.externals = options.dependencies;
/**
* Clear all plugins from CRA webpack conf
*/
const regexp = /(MiniCssExtractPlugin)/;
conf.plugins = conf.plugins
?.map((item) => {
if (item && item.constructor && item.constructor.name && !regexp.test(item.constructor.name)) {
return null;
} else if (item && regexp.test(item.constructor.name)) {
return new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: `${options.mini ? `${fileName}.min` : fileName}.css`,
...options.miniCssExtractPluginOptions,
});
}
return item;
})
.filter(Boolean);
if (!options.mini) {
conf.optimization = {
minimize: false,
minimizer: [],
};
} else {
conf.plugins?.push(new CssMinimizerPlugin({ ...options.cssMinimizerPluginOptions }));
conf.optimization!.minimizer!.push(
new TerserPlugin({
// cache: true,
parallel: true,
// sourceMap: true, // Must be set to true if using source-maps in production
terserOptions: {
// https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions
},
...options.terserPluginOptions,
}),
);
conf.output.filename = minfilename.join('.');
delete conf.optimization?.runtimeChunk;
delete conf.optimization?.splitChunks;
}
}
return conf;
};