|
| 1 | +import { createContext } from "./create-Context"; |
1 | 2 | import fireModule from "./fire-module"; |
2 | | -import { ModuleOptions } from "./interfaces"; |
| 3 | +import { Context, ModuleOptions } from "./interfaces"; |
3 | 4 | /** |
4 | 5 | * 使用模块 |
5 | 6 | * @param moduleData 模块数据,可以是模块定义对象或者是模块资源url. |
6 | 7 | */ |
7 | | -async function useModule(moduleData: ModuleOptions): Promise<void>; |
8 | | -async function useModule(moduleData: string): Promise<void>; |
9 | | -async function useModule(moduleData: any): Promise<void> { |
10 | | - if (!window[Symbol.for("___VML_CONTEXT___")]) { |
11 | | - throw new Error("[vue-module-loader]: 请先使用use方法注册插件。"); |
| 8 | +async function useModule( |
| 9 | + moduleData: ModuleOptions, |
| 10 | + ctx: Context |
| 11 | +): Promise<void>; |
| 12 | +async function useModule(moduleData: string, ctx: Context): Promise<void>; |
| 13 | +async function useModule(moduleData: any, ctx: Context): Promise<void> { |
| 14 | + const existingContext = window[Symbol.for("___VML_CONTEXT___")]; |
| 15 | + if (!existingContext) { |
| 16 | + createContext(ctx); |
12 | 17 | } |
13 | 18 | if (typeof moduleData === "object") { |
14 | 19 | return await fireModule(moduleData); |
15 | 20 | } else if (typeof moduleData === "string") { |
| 21 | + if (!existingContext.Vue) throw new Error("[vue-module-loader]: 上下文对象缺少Vue对象"); |
16 | 22 | const res = await fetch(moduleData); |
17 | 23 | const moduleString = await res.text(); |
18 | | - const moduleCode = moduleString.replace("var", "return"); |
| 24 | + const moduleCode = moduleString.replace("const", "return"); |
19 | 25 | const moduleStringFun = Function(`return function(vue){${moduleCode}}`)(); |
20 | | - const moduleDataFromUrl = moduleStringFun( |
21 | | - window[Symbol.for("___VML_CONTEXT___")].Vue |
22 | | - ); |
| 26 | + const moduleDataFromUrl = moduleStringFun(existingContext.Vue); |
23 | 27 | return await fireModule(moduleDataFromUrl, moduleData.match(/\S*\//)[0]); |
24 | 28 | } |
25 | 29 | } |
|
0 commit comments