ESM导入字符串形式的MJS模块插件

林一二2023年06月14日 20:16
Ref: 2ality
Keywords:
const js = fs.readFileSync(path.join(fileURLToPath(import.meta.url), '../../dist/index.mjs'), 'utf8');
const encodedJs = encodeURIComponent(js);
const dataUri = `data:text/javascript;charset=utf-8,${encodedJs}`;
const importedPlugin = await import(dataUri) as IMemeloopPlugin;
const nodes = Object.values(importedPlugin).filter((classObject): classObject is IBaseNodeConstructor =>
	'pluginMemberType' in classObject && classObject.pluginMemberType === PluginMemberType.GraphNode
);
Code

```ts
const js = fs.readFileSync(path.join(fileURLToPath(import.meta.url), '../../dist/index.mjs'), 'utf8');
const encodedJs = encodeURIComponent(js);
const dataUri = `data:text/javascript;charset=utf-8,${encodedJs}`;
const importedPlugin = await import(dataUri) as IMemeloopPlugin;
const nodes = Object.values(importedPlugin).filter((classObject): classObject is IBaseNodeConstructor =>
	'pluginMemberType' in classObject && classObject.pluginMemberType === PluginMemberType.GraphNode
);
```