Skip to content

Commit

Permalink
feat: support reloadAll
Browse files Browse the repository at this point in the history
  • Loading branch information
cxtom committed Jul 31, 2020
1 parent a155600 commit 955c445
Showing 1 changed file with 47 additions and 22 deletions.
69 changes: 47 additions & 22 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,25 @@ export default class Reloader {
this.updateFiles();
}

reloadAll(newFileMap: IFileMap) {
const reloadModules = new Set<string>();
for (const [name] of Object.entries(this.fileMap)) {
const moduleId = require.resolve(join(this.context, name));
if (require.cache[moduleId]) {
reloadModules.add(moduleId);
}
}
const modulesToReload = Array.from(reloadModules);
if (modulesToReload.length > 0) {
this.del(modulesToReload);
}
this.updateFileMap(Object.assign(this.fileMap, newFileMap));
return {
reloadModules: modulesToReload.map(a => a.replace(this.context + sep, '')),
errors: [],
};
}

reload(newFileMap: IFileMap) {

const reloadModules = new Set<string>();
Expand All @@ -75,30 +94,23 @@ export default class Reloader {

const modulesToReload = Array.from(reloadModules);

const errors: IError[] = [];

if (modulesToReload.length > 0) {
// 删除缓存
batchdelcache(
modulesToReload,
true, this.commonRootPath
);

/* istanbul ignore next */
if (typeof global.gc === 'function') {
global.gc();
}
}

const errors: IError[] = [];
for (const mod of modulesToReload) {
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
require(mod);
}
catch (e) {
errors.push({
file: mod,
code: 1,
});
this.del(modulesToReload);

for (const mod of modulesToReload) {
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
require(mod);
}
catch (e) {
errors.push({
file: mod,
code: 1,
});
}
}
}

Expand All @@ -115,6 +127,19 @@ export default class Reloader {
this.updateFiles();
}

private del(modulesToReload: string[]) {
// 删除缓存
batchdelcache(
modulesToReload,
true, this.commonRootPath
);

/* istanbul ignore next */
if (typeof global.gc === 'function') {
global.gc();
}
}

private getKey(item: IFileMapItem): string {
if (typeof item === 'string') {
return item;
Expand Down

0 comments on commit 955c445

Please sign in to comment.