-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.ts
268 lines (221 loc) · 8 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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import * as path from "path";
import * as fs from "fs";
import { execSync } from "child_process";
const DllPlugin = require("webpack/lib/DllPlugin");
const { green, yellow, red } = require("chalk");
type Options = { dllConfigPath: string, forceBuild?: boolean };
const propOrIdentity = function(prop: string, input: any): any {
return input[prop] || input
}
const rootPath = process.cwd();
const cacheFile = path.join(__dirname, "_cache.json");
const cacheData: { entry?: any, dependencies?: any; hash?: string; } = {
entry: {},
dependencies: {}
};
const packageFile = path.join(__dirname, "../../package.json");
let packageData: any = {};
const outputEntryNames: any[] = [];
let existPackageFile: boolean;
let existCacheFile: boolean;
let oldCacheData: any = {};
let dllConfigPath: string;
let dllPlugin: any;
function WebpackBuildDllPlugin(newOptions: any) {
const defaultOptions: Options = { dllConfigPath: "", forceBuild: false };
const options: Options = { ...defaultOptions, ...newOptions };
this.options = options;
dllConfigPath = options.dllConfigPath;
if (dllConfigPath) {
dllConfigPath = path.isAbsolute(dllConfigPath) ? dllConfigPath : path.join(rootPath, dllConfigPath);
if (!fs.existsSync(dllConfigPath)) {
throw Error("[webpack-build-dll-plugin] not found DllConfigPath.\n");
}
} else {
throw Error("[webpack-build-dll-plugin] please set DllConfigPath.\n");
}
const dllConfig: any = propOrIdentity('default', require(dllConfigPath));
const configKeys = ["entry", "output", "plugins"];
for (const configKey of configKeys) {
if (!(configKey in dllConfig)) {
throw Error(`DllReference config is required: ${configKey}`);
}
}
const { entry, plugins } = dllConfig;
if (Array.isArray(entry)) {
throw new Error("DllPlugin: supply an Array as entry");
}
for (const plugin of plugins) {
if (plugin instanceof DllPlugin) {
dllPlugin = plugin;
break;
}
}
if (dllPlugin === void 0) {
throw Error("Not Found DllReference Plugin.");
}
if (options.forceBuild) {
console.log(yellow("[webpack-build-dll-plugin] config forceBuild: true, will rebuild DllReference files in starting."));
buildDllReferenceFiles();
} else {
checkFilesBuilded(dllConfig);
}
}
function checkFilesBuilded(dllConfig: any) {
const { entry, output } = dllConfig;
const entryNames = Object.keys(entry);
const buildJSFiles = [];
const manifestFiles = [];
try {
packageData = JSON.parse(fs.readFileSync(packageFile, "utf8"));
} catch (error) { console.error(red(error)); }
const getModuleVersion = (moduleName: string) => {
const moduleVersion = packageData.dependencies[moduleName];
if (moduleVersion === void 0) {
console.error(red(`[webpack-build-dll-plugin] missing ${moduleName} version in your package.json file.\n`));
return "";
} else {
return moduleVersion;
}
};
for (const entryName of entryNames) {
const outputEntryName = output.filename.replace("[name]", entryName);
outputEntryNames.push(outputEntryName);
buildJSFiles.push(
path.join(...[
...(path.isAbsolute(output.path) ? [] : [dllConfigPath, "../"]),
output.path,
outputEntryName
])
);
const manifestFileName = dllPlugin.options.path.replace("[name]", entryName);
manifestFiles.push(
path.isAbsolute(manifestFileName) ? manifestFileName : path.join(dllConfigPath, "../", manifestFileName)
);
cacheData.entry[outputEntryName] = entry[entryName].map((moduleName: string) => ({
[moduleName]: getModuleVersion(moduleName)
})).reduce((prevObj: any, currObj: any) => ({ ...prevObj, ...currObj }), {});
}
const allBuildFiles = [...buildJSFiles, ...manifestFiles];
const hashPattern = /\[hash\:\s?\d*\]/;
let hashLimit: any;
let oldHash: string;
const haveHashFilename = hashPattern.test(output.filename);
if (haveHashFilename) {
console.log(yellow("[webpack-build-dll-plugin] your filename have [hash] name...\n"));
try {
oldCacheData = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
} catch (error) {}
oldHash = oldCacheData.hash;
const limitPattern = /(?:\[hash\:\s?)(\d+)\]/;
hashLimit = limitPattern.test(output.filename) && limitPattern.exec(output.filename)[1];
if (!oldHash) {
console.log(yellow("[webpack-build-dll-plugin] not find [hash] name, will build DllReferenceFiles...\n"));
const buffer = buildDllReferenceFiles(false);
let currHash = "";
const loggerHashPattern = /(?:Hash\:\s)(\w+)/;
if (loggerHashPattern.test(buffer)) {
currHash = loggerHashPattern.exec(buffer)[1];
cacheData.hash = currHash;
console.log(currHash);
writeCacheFile();
}
return;
}
}
let allFileBuilded = true;
for (let buildFile of allBuildFiles) {
if (haveHashFilename && hashPattern.test(buildFile)) {
buildFile = buildFile.replace(hashPattern, hashLimit ? oldHash.slice(0 , hashLimit) : oldHash);
}
if (!fs.existsSync(buildFile)) {
console.error(red(`[webpack-build-dll-plugin] missing build file: ${buildFile}, will rebuild DllReference files.`));
buildDllReferenceFiles();
allFileBuilded = false;
break;
}
}
if (allFileBuilded) {
console.log(yellow("[webpack-build-dll-plugin] DllReference files is already builded.\n"));
checkEntryModules(entry);
}
}
function checkEntryModules(entry: any) {
console.log(yellow("[webpack-build-dll-plugin] now checking entry modules & dependencies different...\n"));
existPackageFile = fs.existsSync(packageFile);
existCacheFile = fs.existsSync(cacheFile);
if (!existPackageFile) {
console.error(red("[webpack-build-dll-plugin] cannot find your package.json file in project...\n"));
return;
}
if (!existCacheFile) {
console.log(yellow("[webpack-build-dll-plugin] cannot find old cache data, will rebuild new DllReference & new entry modules & dependencies cache data...\n"));
buildDllReferenceFiles();
return;
}
if (existPackageFile && existCacheFile) {
let isSameModule = true;
try {
oldCacheData = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
} catch (error) { console.error(red(error)); }
if (!("entry" in oldCacheData && "dependencies" in oldCacheData)) {
console.log(yellow("[webpack-build-dll-plugin] entry & dependencies is not in cache data, will rebuild DllReferenceFiles...\n"));
buildDllReferenceFiles();
return;
}
const entryNames = Object.keys(cacheData.entry);
const oldEntryNames = Object.keys(oldCacheData.entry);
for (const entryName of entryNames) {
const entryModules = cacheData.entry[entryName];
const oldEntryModules = oldCacheData.entry[entryName];
if (oldEntryNames.indexOf(entryName) > -1) {
const moduleNames = Object.keys(entryModules);
const oldModuleNames = Object.keys(oldEntryModules);
if (moduleNames.length === oldModuleNames.length) {
for (const moduleName of moduleNames) {
if (entryModules[moduleName] !== oldEntryModules[moduleName]) {
isSameModule = false;
break;
}
}
} else {
isSameModule = false;
}
} else {
oldCacheData.entry[entryName] = cacheData.entry[entryName];
cacheData.entry = oldCacheData.entry;
isSameModule = false;
}
if (!isSameModule) {
console.log(yellow(`[webpack-build-dll-plugin] your dllConfig entry ${entryName} modules version is look changed, wil rebuild DllReferenceFiles...`));
buildDllReferenceFiles();
}
}
if (isSameModule) {
console.log(green("[webpack-build-dll-plugin] your entry & modules is look the same, DllReference will not rebuild.\n"));
}
}
}
function buildDllReferenceFiles(canWriteCache = true) {
try {
const logger: Buffer = execSync(`webpack --config ${dllConfigPath}`);
if (canWriteCache) {
writeCacheFile();
}
if (logger) {
console.log(green(logger));
console.log(yellow("[webpack-build-dll-plugin] DllReference is built.\n"));
}
return logger;
} catch (ex) {
console.error(ex.stdout);
return ex.stdout;
}
}
function writeCacheFile() {
fs.writeFile(cacheFile, JSON.stringify(cacheData, null, 2), () => {
console.log(green(`[webpack-build-dll-plugin] cacheFile is saved.`));
});
}
WebpackBuildDllPlugin.prototype.apply = function(compiler: any) {};
module.exports = WebpackBuildDllPlugin;