Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release: stark-module-1.5.1 #507

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 6
version: 7

- run: pnpm run setup
- run: pnpm run lint
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
"scripts": {
"preinstall": "npx only-allow pnpm",
"setup": "rm -rf node_modules && rm -rf ./packages/*/node_modules && pnpm i --registry=https://registry.npmmirror.com && npm run build",
"build": "pnpm run clean && pnpm -r --filter ./packages run build",
"watch": "pnpm -r --filter ./packages --parallel run watch",
"build": "pnpm run clean && pnpm --filter=./packages/* run build",
"watch": "pnpm --parallel --filter=./packages/* run watch",
"clean": "rimraf packages/*/lib",
"publish:packages": "ts-node ./scripts/publish.ts",
"publish:beta": "ts-node ./scripts/beta.ts",
Expand Down
4 changes: 3 additions & 1 deletion packages/icestark-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@
"url": "git+https://github.com/ice-lab/icestark.git"
},
"devDependencies": {
"typescript": "^3.4.4"
"typescript": "^4.3.5",
"react": "^16.0.0",
"@types/react": "^16.0.0"
},
"jest": {
"coverageDirectory": "./coverage/",
Expand Down
2 changes: 1 addition & 1 deletion packages/icestark-data/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"url": "git+https://github.com/ice-lab/icestark.git"
},
"devDependencies": {
"typescript": "^3.4.4"
"typescript": "^4.3.5"
},
"jest": {
"coverageDirectory": "./coverage/",
Expand Down
5 changes: 5 additions & 0 deletions packages/icestark-module/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## 1.5.1

- [fix] rerender module when props changed
- [fix] get latest props after load module bundles

## 1.5.0

- [fix] exports all library exports. ([#469](https://github.com/ice-lab/icestark/pull/469))
Expand Down
39 changes: 36 additions & 3 deletions packages/icestark-module/__tests__/index.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {
unmoutModule,
removeCSS,
registerModule,
registerModules,
} from '../src/modules';
import MicroModule, { renderModules, renderComponent } from '../src/MicroModule';

Expand All @@ -33,6 +32,23 @@ const defaultUnmount = (targetNode: HTMLElement) => {
ReactDOM.unmountComponentAtNode(targetNode);
};

const TestModule = ({ value = 1 }: { value?: number }) => {
console.log('hhj-log', 'value', value);
return <span>{value}</span>;
};

const TestHost = ({ initialValue }: { initialValue: number }) => {
const [value, setValue] = React.useState<number>(initialValue);

React.useEffect(() => {
setTimeout(() => {
setValue((value) => value + 1);
}, 500);
}, []);

return <MicroModule moduleName="moduleA" value={value} />;
};

const modules = [{
name: 'selfComponent',
url: 'http://127.0.0.1:3334/index.js',
Expand Down Expand Up @@ -108,7 +124,7 @@ describe('render modules', () => {
expect(container.innerHTML).toBe('<div><div><h2>404</h2></div></div>');
next();
}, 0);
});
});

test('render MicroModule with custom className and style', (next) => {
const { container } = render(<MicroModule moduleName="selfComponent" wrapperClassName="test" wrapperStyle={{ fontSize: '14px' }} sandbox />);
Expand Down Expand Up @@ -183,8 +199,25 @@ describe('render modules', () => {
});
})

test('props rerender', async () => {
registerModule({
name: 'moduleA',
render: (props: any) => {
return <TestModule {...props}/>
},
});
const { container } = render(<TestHost initialValue={5} />);
expect(container.innerHTML).toBe('<div><span>5</span></div>');
await new Promise<void>((resolve) => {
setTimeout(() => {
expect(container.innerHTML).toBe('<div><span>6</span></div>');
resolve();
}, 2000);
});
});

test('clear module', () => {
clearModules();
expect(getModules()).toStrictEqual([]);
});
});
});
6 changes: 4 additions & 2 deletions packages/icestark-module/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ice/stark-module",
"version": "1.5.0",
"version": "1.5.1",
"description": "toolkit for load standard micro-module",
"main": "lib/index.js",
"scripts": {
Expand Down Expand Up @@ -34,7 +34,9 @@
"devDependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1",
"typescript": "^3.8.3"
"typescript": "^4.3.5",
"@types/react": "^16.0.0",
"@types/react-dom": "^16.0.0"
},
"dependencies": {
"@ice/sandbox": "^1.1.0"
Expand Down
30 changes: 22 additions & 8 deletions packages/icestark-module/src/MicroModule.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ export default class MicroModule extends React.Component<any, State> {

private unmout = false;

// moduleInfo 中定义的 mount 函数
private moduleLifecycleMount = null;

// 从 moduleInfo 配置中解析得到的模块组件
private moduleComponent = null;

constructor(props) {
super(props);
this.state = {
Expand All @@ -45,9 +51,16 @@ export default class MicroModule extends React.Component<any, State> {
}

componentDidUpdate(prevProps) {
if (!shallowCompare(prevProps.moduleInfo || {}, this.props.moduleInfo || {})) {
const { moduleInfo: preModuleInfo = {}, ...preRest } = prevProps;
const { moduleInfo: curModuleInfo = {}, ...curRest } = this.props;

if (!shallowCompare(preModuleInfo, curModuleInfo)) {
this.mountModule();
}
if (!shallowCompare(preRest, curRest)) {
// 对于除 moduleInfo 外的 props 更新,重新渲染模块
this.moduleLifecycleMount && this.moduleLifecycleMount(this.moduleComponent, this.mountNode, curRest);
}
}

componentWillUnmount() {
Expand Down Expand Up @@ -79,9 +92,6 @@ export default class MicroModule extends React.Component<any, State> {
}

async mountModule() {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { sandbox, moduleInfo, wrapperClassName, wrapperStyle, loadingComponent, handleError, ...rest } = this.props;

if (!this.moduleInfo) {
console.error(`Can't find ${this.props.moduleName} module in modules config`);
return;
Expand All @@ -93,20 +103,24 @@ export default class MicroModule extends React.Component<any, State> {
this.setState({ loading: true });

try {
const { mount, component } = await loadModule(this.moduleInfo, sandbox);
const { mount, component } = await loadModule(this.moduleInfo, this.props.sandbox);
const lifecycleMount = mount;
this.moduleLifecycleMount = mount;
this.moduleComponent = component;

!this.unmout && this.setState({ loading: false });
if (lifecycleMount && component) {
if (this.unmout) {
unmoutModule(this.moduleInfo, this.mountNode);
} else {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { sandbox, moduleInfo, wrapperClassName, wrapperStyle, loadingComponent, handleError, ...rest } = this.props;
lifecycleMount(component, this.mountNode, rest);
}
}
} catch (err) {
this.setState({ loading: false });
handleError(err);
this.props.handleError(err);
}
}
}
Expand All @@ -120,7 +134,7 @@ export default class MicroModule extends React.Component<any, State> {
const { loading } = this.state;
const { render } = this.moduleInfo || {};

const { wrapperClassName, wrapperStyle, loadingComponent } = this.props;
const { wrapperClassName, wrapperStyle, loadingComponent, ...restProps } = this.props;
return loading
? loadingComponent
: (
Expand All @@ -129,7 +143,7 @@ export default class MicroModule extends React.Component<any, State> {
style={wrapperStyle}
ref={(ref) => { this.mountNode = ref; }}
>
{ this.moduleInfo && this.validateRender() && render() }
{ this.moduleInfo && this.validateRender() && render(restProps) }
</div>
);
}
Expand Down
25 changes: 25 additions & 0 deletions packages/icestark-module/src/eventHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* CustomEvent Polyfill for IE.
* See https://gist.github.com/gt3/787767e8cbf0451716a189cdcb2a0d08.
*/
(function () {
if (typeof (window as any).CustomEvent === 'function') return false;

function CustomEvent(event, params) {
params = params || { bubbles: false, cancelable: false, detail: null };
const evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
}

(window as any).CustomEvent = CustomEvent;
})();


export function dispatchEvent(mark: string, params: Record<'detail', object>) {
return window.dispatchEvent(new CustomEvent(mark, params));
}

export function resolveEvent(mark: string) {
return new Promise((resolve) => window.addEventListener(mark, resolve));
}
13 changes: 9 additions & 4 deletions packages/icestark-module/src/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,20 @@ function shouldSkipProperty(p, globalWindow) {
|| isIE11 && globalWindow[p] && typeof window !== 'undefined' && globalWindow[p].parent === window;
}

export function getGlobalProp(globalWindow) {
let cnt = 0;

export function getGlobalProp(globalWindow, checker: (property: unknown) => boolean) {
let cnt = -1;
let lastProp;
// eslint-disable-next-line no-restricted-syntax
for (const p in globalWindow) {
// do not check frames cause it could be removed during import
if (shouldSkipProperty(p, globalWindow)) { continue; }
if (cnt === 0 && p !== firstGlobalProp || cnt === 1 && p !== secondGlobalProp) { return p; }
cnt++;
const isValidLibraryExport = checker(globalWindow[p]);
if (!isValidLibraryExport) {
continue;
}
if (cnt === 0 && p !== firstGlobalProp || cnt === 1 && p !== secondGlobalProp) { return p; }
lastProp = p;
}
if (lastProp !== lastGlobalProp) {
Expand All @@ -31,7 +36,7 @@ export function getGlobalProp(globalWindow) {
// polyfill for UC browser which lastprops will alway be window
// eslint-disable-next-line no-restricted-syntax
for (const p in globalWindow) {
if (!noteGlobalKeys.includes(p)) {
if (!noteGlobalKeys.includes(p) && checker(globalWindow[p])) {
lastProp = p;
}
}
Expand Down
5 changes: 4 additions & 1 deletion packages/icestark-module/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
clearModules,
} from './modules';
import MicroModule from './MicroModule';
import { preloadModules } from './preload';

export {
StarkModule,
Expand All @@ -18,4 +19,6 @@ export {
getModules,
mountModule,
unmoutModule,
};
preloadModules,
};

11 changes: 6 additions & 5 deletions packages/icestark-module/src/loader.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Sandbox from '@ice/sandbox';
import { getGlobalProp, noteGlobalProps } from './global';
import { StarkModule } from './modules';
import { isEsModule } from './utils';

export interface ImportTask {
[name: string]: Promise<string[]>;
Expand Down Expand Up @@ -51,13 +52,13 @@ export default class ModuleLoader {
} else {
globalWindow = window;
}
const { name } = starkModule;
const { name, loadModuleByName } = starkModule;
let libraryExport = '';
// excute script in order
try {
sources.forEach((source, index) => {
const lastScript = index === sources.length - 1;
if (lastScript) {
if (lastScript && !loadModuleByName) {
noteGlobalProps(globalWindow);
}
// check sandbox
Expand All @@ -68,14 +69,14 @@ export default class ModuleLoader {
// eslint-disable-next-line no-eval
(0, eval)(source);
}
if (lastScript) {
libraryExport = getGlobalProp(globalWindow);
if (lastScript && !loadModuleByName) {
libraryExport = getGlobalProp(globalWindow, isEsModule);
}
});
} catch (err) {
console.error(err);
}
const moduleInfo = libraryExport ? (globalWindow as any)[libraryExport] : ((globalWindow as any)[name] || {});
const moduleInfo = libraryExport ? (globalWindow as any)[libraryExport] : ((globalWindow as any)[name]);
// remove moduleInfo from globalWindow in case of excute multi module in globalWindow
if ((globalWindow as any)[libraryExport]) {
delete globalWindow[libraryExport];
Expand Down
Loading
Loading