{"id":20623471,"url":"https://github.com/gxlmyacc/import-remote","last_synced_at":"2025-08-01T02:11:10.131Z","repository":{"id":38985219,"uuid":"268752926","full_name":"gxlmyacc/import-remote","owner":"gxlmyacc","description":"import remote module","archived":false,"fork":false,"pushed_at":"2024-05-23T08:34:59.000Z","size":3601,"stargazers_count":23,"open_issues_count":16,"forks_count":5,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-08T20:02:43.669Z","etag":null,"topics":["import-remote","micro-frontend","react","webpack","webpack-plugin"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gxlmyacc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-06-02T09:06:01.000Z","updated_at":"2024-10-11T03:31:56.000Z","dependencies_parsed_at":"2024-10-29T19:04:59.744Z","dependency_job_id":null,"html_url":"https://github.com/gxlmyacc/import-remote","commit_stats":{"total_commits":320,"total_committers":2,"mean_commits":160.0,"dds":"0.38749999999999996","last_synced_commit":"291b5ab43307689aea1e554111cfc634d1515752"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gxlmyacc%2Fimport-remote","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gxlmyacc%2Fimport-remote/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gxlmyacc%2Fimport-remote/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gxlmyacc%2Fimport-remote/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gxlmyacc","download_url":"https://codeload.github.com/gxlmyacc/import-remote/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249072827,"owners_count":21208253,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["import-remote","micro-frontend","react","webpack","webpack-plugin"],"created_at":"2024-11-16T12:27:17.770Z","updated_at":"2025-04-15T12:37:23.375Z","avatar_url":"https://github.com/gxlmyacc.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# import-remote\n\n一个远程加载JS模块的库。支持webpack4/5，可以通过使你的项目支持微前端架构。\n\n[![NPM version](https://img.shields.io/npm/v/import-remote.svg?style=flat)](https://npmjs.com/package/import-remote)\n[![NPM downloads](https://img.shields.io/npm/dm/import-remote.svg?style=flat)](https://npmjs.com/package/import-remote)\n\n## 说明\n\n它的初衷是：\n\n  - 希望像`html-webpack-plugin`插件生成HTML入口文件那样生成一个JS入口文件；\n\n  - 插件的配置参数基本和`html-webpack-plugin`保持一致，以便只需将`html-webpack-plugin`插件替换为`import-remote/plugin`插件即可在`html`和`JS`入口间切换；\n\n  - 解决JS模块依赖传递的问题：不再是通过`window`变量来传递依赖；\n\n  - 支持自动从公共包中加载依赖；\n\n  - 利于`webpack`的懒加载功能实现公共包中的导出组件按需加载；\n\n  - 提供`global.xxx`、`window.xxx`这些全局变量私有化作用域的功能，避免污染`window`；\n\n  - 为`JS/CSS`动态添加`publicPath`，方便一份打包成果多处部署；\n\n  - `JS/CSS`资源异步获取，避免通过`script`、`link`加载资源导致的同步加载；\n\n  - 支持多入口文件，实现多模块代码/作用域共享;\n\n### 和`html-webpack-plugin`的区别\n\n  - `html-webpack-plugin`生成的是HTML入口；`import-remote/plugin`生成的JS入口；\n\n  - HTML入口通过浏览器或`iframe`标签加载；JS入口通过`import-remote`提供的加载方法(`remote`)加载；\n\n### 和`webpack library`打包的区别\n\n  - `webpack library`的入口JS可以直接通过`script`标签加载，支持资源跨域；`import-remote`的入口JS需要专门提供的加载方法(`remote`)加载，该方法通过`ajax`请求加载资源，所以资源间的跨域问题需要使用者自行解决；\n\n  - `webpack library`的模块依赖需要通过从`window`变量获取；`import-remote`的模块依赖只需在加载方法(`remote`)中传递进去即可；\n\n  - `webpack library`包必须配置`publicPath`；`import-remote`无需配置`publicPath`或只需配置为`/`，加载方法(`remote`)在加载资源时会自动配置JS的`publicPath，并且查找CSS源代码中的相对路径，将其替换为绝对路径；\n\n### 和`webpack Module Fedetation`打包的区别\n\n  - `webpack Module Fedetation` 需要应用和宿主都是`webpack5`，`import-remote`没有这个要求，`webpack4/5`都可以，甚至宿主的打包环境使用的不是`webpack`(gulp、vite等)也没问题；\n\n### 实现原理\n\n#### 构建期\n\n参考`html-webpack-plugin`生成的js入口里，实际上是该入口依赖的mainfest信息，包含入口JS/CSS文件、external等信息；\n\n#### 加载期\n  \n`import-remote`的加载方法调用时：\n  1. 加载入口JS文件；\n  2. 根据入口JS里的信息，通过ajax请求下载入口JS/CSS资源;\n  3. 通过内置的重写`webpack运行时`加载相关资源;\n  4. 根据`external`信息，替换调加载模块中的这些外部模块；\n  5. 调用入口模块，获取它的`modlule.exports`;\n  6. 返回获取到的`modlule.exports`；\n\n![说明](./images/principle.png)\n\n## 安装\n\n```bash\n  npm install --save import-remote\n```\n\n或者：\n\n```bash\n  yarn add import-remote\n```\n\n## 插件使用说明\n\n通过`import-remote/plugin`插件可以为你的`webpack`包生成一个JS入口文件。下面是一个`webpack`配置示例:\n\n**webpack.config.js**\n\n```js\nconst ImportRemotePlugin = require('import-remote/plugin')\n\nconst entryFiles = ['index', 'foo', 'bar'];\n\nmodule.exports = {\n  // 配置入口，可以配置多个入口\n  entry: {\n    ...(entryFiles.reduce((p, file) =\u003e {\n      p[file] = `${file}.js`;\n      return p;\n    }, {}))\n  }\n  // 配置输出目录\n  output: {\n    path: __dirname + '/dist',\n    filename: 'assets/[name]-[chunkhash:5].js',\n    chunkFilename: 'assets/[name]-[chunkhash:5]-chunk.js',\n  },\n  // 配置外部依赖\n  externals: [\n    'react',\n    'react-dom',\n    'lodash'\n  ],\n  plugins: [\n    // 装载插件\n    ...entryFiles.map(file =\u003e new ImportRemotePlugin({\n      template: `auto`,\n      // 生成的入口文件名\n      filename: `${file}.js`,\n      // 包含的入口chunk\n      chunks: [file],\n    }))\n    \n  ]\n}\n```\n\n入口文件示例：\n\n**src/index.js**\n\n```js\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport _ from 'lodash',\n\nconst test = {\n  dosomething() {\n    console.log('dosomething', React, ReactDOM, _);\n  }\n}\n\n// 导出你要导出的内容\nmodule.exports = test;\n```\n\n**宿主端使用示例**\n\n```js\nimport remote from 'import-remote';\n\nasync function run() {\n  // 通过await等待模块加载完毕\n  const testIndex = await remote('http://localhost:3000/test/index.js', {\n    // 配置模块需要依赖\n    externals: { \n      react: require('react'), \n      'react-dom': require('react-dom'),\n      'lodash': require('lodash'),\n    }\n  });\n  // 拿到模块输出对象后，即可做你想做的任何事了\n  testIndex.dosomething();\n\n  // 也可以将依赖配置成全局依赖，这样importRemote时就不必再传依赖了\n  Object.assign(remote.externals, { \n    react: require('react'), \n    'react-dom': require('react-dom'),\n    'lodash': require('lodash'),\n  });\n  const testOther = await remote('http://localhost:3000/test/other.js');\n  testOther.dosomething();\n}\n\nrun();\n```\n\n`import-remote`还提供了远程模块(`RemoteModule`)类，方便管理同一组模块：\n\n```js\nimport { RemoteModule } from 'import-remote';\n\n// 配置RemoteModule的host和依赖\nconst testModule = new RemoteModule('http://localhost:3000/test', {\n  externals: { \n    react: require('react'), \n    'react-dom': require('react-dom'),\n    'lodash': require('lodash'),\n  }\n});\n\n// 具体的加载路径为RemoteModule的`${host}${requireName}.js`\nconst testIndex = await testModule.require('index');\nconst testOther = await testModule.require('other');\n\ntestIndex.dosomething();\ntestOther.dosomething();\n\n```\n\n### remote/RemoteModule的options\n\n- `scopeName: string` - 作用域名，不配置时，会使用远程模块项目的项目名(`package.json-\u003ename`)；\n\n- `timeout:number` - 资源加载的请求时间，为0表示不会超时；\n\n- `externals: Record\u003cstring, any\u003e` - 传递给远程模块的依赖模块(webpack配置的externals)；\n\n- `getManifestCallback: (manifest: RemoteManifest) =\u003e any|Promise\u003cany\u003e` - 当加载到`manifest`后的回调函数；\n\n- `afterCreateRuntime: (webpack_require: any, ctx: RemoteModuleRuntime) =\u003e void` - 模块的runtime创建好后的回调函数；\n\n- `host: string` - 远程模块的`host`，相同`host`的远程模块会认为来自同一个项目，它们会共享同一个runtime运行时。当不传时，host将从url中去取(去掉url中最后一个`/`前的部分会认为是`host`);\n\n- `sync: boolean` - 使用使用`ajax`的同步请求来加载资源；\n\n- `cacheDB: boolean` - 是否开启`cacheDB`，当开启后，每次加载成功的远程资源会保存在一个名叫`import-remote-global-db`的`indexedDB`数据库中，当遇到某个资源ajax请求失败，`xhr.status`为`0`时，将会改为尝试从该数据库加载该资源。该数据每次启动时会清楚一个月之前的缓存，以避免缓存资源膨胀。\n  \n  `注`：你也可以通过`import-remote/cache`导出的`enableCacheDB`方法来为所有模块开启`cacheDB`；\n```js\nimport { enableCacheDB } from 'import-remote/cache';\n\nenableCacheDB();\n```\n\n- `useEsModuleDefault: boolean` - 是否在加载到远程模块后直接返回入口模块的`default`导出，而不是返回整个该入口模块；\n\n### `import-remote/plugin`插件基本配置选项\n\n`import-remote/plugin`的基本配置选项基本和`html-webpack-plugin`一致，这样目的是方便两个插件间切换。\n\n|属性名|类型|默认值|说明|\n|:--:|:--:|:-----:|:----------|\n|**`filename`**|`{String}`|`'index.js'`|生成的入口文件名。默认为`index.js`. 你也可以在这里指的子目录 (比如: `entrys/index.js`)|\n|**`hash`**|`{Boolean}`|`false`|如果值为true，就添加一个唯一的webpack compilation hash给所有JS和CSS文件。这对缓存清除（cache busting）十分有用|\n|**`cache`**|`{Boolean}`|`true`|如果为true (默认)，只要文件被更改了就生成文件|\n|**`showErrors`**|`{Boolean}`|`true`|如果为true (默认)，详细的错误信息将被写入到JS文件中|\n|**`chunks`**|`{?}`|`?`|允许你只添加某些chunks(e.g only the unit-test chunk)|\n|**[`chunksSortMode`](#plugins)**|`{String\\|Function}`|`auto`|在chunks被include到html文件中以前，允许你控制chunks 应当如何被排序。允许的值: `none`|`auto`|`dependency`|{Function} - 默认值: `auto`|\n|**`excludeChunks`**|`{Array.\u003cstring\u003e}`|``|允许你跳过某些chunks (e.g don't add the unit-test chunk)|\n|**`entriesManifest`**|`{Boolean|String}`|`''`|当该参数为true时，将为项目生成一个所有入口的说明文件(默认文件名`import-remote-entries.js`),你可以通过通过`RemoteModule`的`requireEntries`方法加载该文件来获取该项目目前存在的所有入口文件信息|\n|**`libraryFileName`**|`{Boolean|String}`|`''`|当该参数为true时，将会将本包打包的`import-remote.min.js`文件复制到打包目标目录中，你可以通过`import AsyncRemoteModule from \"import-remote/esm/fetch\";`，先通过它远程加载`import-remote.min.js`后再加载实际的远程入口，已避免`import-remote`升级后需要宿主也升级`import-remote`的问题|\n\n#### 生成多输出入口文件\n\n要生成多个输出入口文件，只需要在你的插件列表中配置多个`ImportRemotePlugin`插件：\n\n```js\n{\n  entry: 'index.js',\n  output: {\n    path: __dirname + '/dist',\n    filename: 'index_bundle.js'\n  },\n  plugins: [\n    new ImportRemotePlugin(), // 生成默认的index.js\n    new ImportRemotePlugin({  // 同时生成一个test.js\n      filename: 'test.js',\n    })\n  ]\n}\n```\n\n#### 过滤Chunks\n\n要只打包特定的chunk包，你可以通过`chunks`属性来控制：\n\n```js\nplugins: [\n  new ImportRemotePlugin({\n    chunks: ['app']\n  })\n]\n```\n\n你也可以配置要排除特定的包，通过`excludeChunks`选项来控制：\n\n```js\nplugins: [\n  new ImportRemotePlugin({\n    excludeChunks: [ 'dev-helper' ]\n  })\n]\n```\n\n#### 长期缓存\n\n要支持长期缓存，你可以通过为`filename`添加`contenthash/templatehash`：\n\n```js\nplugins: [\n  new ImportRemotePlugin({\n    filename: 'index.[contenthash].js'\n  })\n]\n```\n\n`contenthash/templatehash` 是输出文件内容的hash。\n\n另外, 你也可以这样配置hash： `[\u003chashType\u003e:contenthash:\u003cdigestType\u003e:\u003clength\u003e]`\n\n* `hashType` - `sha1`、`md5`、`sha256`、`sha512`之一，或者任意一种node.js支持的hash类型\n* `digestType` - `hex`、`base26`、`base32`、`base36`、`base49`、`base52`、`base58`、 `base62`、`base64`之一\n* `maxlength` - 生成的hash字符的最大程度\n\n**默认为:** `[md5:contenthash:hex:9999]`\n\n\n### `import-remote/plugin`插件额外配置选项\n\n除了从`html-webpack-plugin`继承的配置选项，`import-remote/plugin`也提供了一些自己的配置选项：\n\n|属性名|类型|默认值|说明|\n|:--:|:--:|:-----:|:----------|\n|**`commonModules`**|`[{ name?: string, url: string, scoped?: boolean }]`|`[]`|依赖的公共模块，如果配置了公共模块，则模块的依赖将尝试从这些公共模块中加载依赖。其中`name`是可选参数，为某个外部依赖模块名，如果配置了`name`，表示该公共包只是该名称的模块，则只有该模块依赖该名称的外部依赖模块时才会加载该模块包。该功能依赖于webpack的externals|\n|**`shareModules`**|`[string or { name: string, var: string }]`|`[]`|共享模块列表，如果配置了共享模块，则模块的这些依赖将优先使用宿主应用externals参数中传递的依赖，如果未在宿主应用中找到，才使用自己的该模块。该功能不依赖webpack的externals。\n|**`globalToScopes`**|`string[]`|`[]`|需要局部化的全局变量，该数组中声明的名称，在加载资源时将会从源代码中将其替换为从某个私有变量中读取这些值|\n\n\n#### 公共模块包\n\n提供公共模块包的目的是方便公共模块的共享，同时利用`webpack`的懒加载功能实现组件的按需加载。\n\n这是一个公共模块包的示例：\n****\n```js\n// index.js\nimport { createRequireFactory } from 'import-remote';\n\nexport default createRequireFactory({\n  'import-remote': () =\u003e require('import-remote'),\n  react: () =\u003e import(/* webpackChunkName: 'react' */ 'react'),\n  'react-dom': () =\u003e import(/* webpackChunkName: 'react-dom' */ 'react-dom'),\n  'prop-types': () =\u003e import(/* webpackChunkName: 'prop-types' */ 'prop-types'),\n  mobx: () =\u003e import(/* webpackChunkName: 'mobx' */ 'mobx'),\n  'mobx-react': () =\u003e import(/* webpackChunkName: 'mobx-react' */ 'mobx-react'),\n  qs: () =\u003e import(/* webpackChunkName: 'qs' */ 'qs'),\n});\n\n```\n\n**webpack.config.js**\n\n```js\nconst ImportRemotePlugin = require('import-remote/plugin')\n\nmodule.exports = {\n  entry: {\n    index: 'index.js'\n  }\n  output: {\n    filename: '[name]-[chunkhash:5].js'\n  },\n  externals: [\n    {\n      'import-remote': {\n        root: 'importRemote',\n        amd: 'import-remote',\n        commonjs2: 'import-remote',\n        commonjs: 'import-remote',\n      },\n    },\n  ],\n  plugins: [\n    new ImportRemotePlugin()\n  ]\n}\n```\n\n这是一个公共lib模块包的示例：\n****\n```js\n// index.js\nimport axios from 'axios';\n\nexport default axios;\n```\n\n**webpack.config.js**\n\n```js\nconst ImportRemotePlugin = require('import-remote/plugin')\n\nmodule.exports = {\n  entry: {\n    index: 'index.js'\n  }\n  output: {\n    filename: '[name]-[chunkhash:5].js'\n  },\n  plugins: [\n    new ImportRemotePlugin()\n  ]\n}\n```\n\n一个依赖公共包的webpack配置如下：\n\n**webpack.config.js**\n\n```js\nconst ImportRemotePlugin = require('import-remote/plugin')\n\nmodule.exports = {\n  entry: {\n    index: 'index.js'\n  }\n  output: {\n    filename: '[name]-[chunkhash:5].js'\n  },\n  externals: {\n    react: {\n      root: 'React',\n      amd: 'react',\n      commonjs2: 'react',\n      commonjs: 'react',\n    },\n    'react-dom': {\n      root: 'ReactDOM',\n      amd: 'react-dom',\n      commonjs2: 'react-dom',\n      commonjs: 'react-dom',\n    },\n    mobx: {\n      root: 'mobx',\n      commonjs: 'mobx',\n      commonjs2: 'mobx',\n    },\n    'mobx-react': {\n      root: 'mobxReact',\n      commonjs: 'mobx-react',\n      commonjs2: 'mobx-react',\n    },\n  },\n  plugins: [\n    new ImportRemotePlugin({\n      commonModules: [\n        // 当指定了name时，只有该name在externals中存在时，才会加载该公共包\n        { name: 'axios', url: 'http://localhost:3000/lib/axios.min.js' },\n        // 未指定name事，只要externals不为空，就会加载该公共包\n        { url: 'http://localhost:3000/lib/commonLibs.js' },\n      ]\n    })\n  ]\n}\n```\n\n则这个模块的依赖：\n\n  1. 首先从宿主使用加载方法`remote`中配置的`externals`中寻找依赖；\n\n  2. 第一步没找到依赖，将会从模块中寻找依赖；\n\n#### 共享模块\n\n通过共享模块，使多个远程应用间使用共同的依赖。\n\n这是一个共享模块包的配置示例：\n\n**webpack.config.js**\n\n```js\nconst ImportRemotePlugin = require('import-remote/plugin')\n\nmodule.exports = {\n  entry: {\n    index: 'index.js'\n  }\n  output: {\n    filename: '[name]-[chunkhash:5].js'\n  },\n  plugins: [\n    new ImportRemotePlugin({\n      shareModules: [\n        { name: 'react', var: 'react' },\n        { name: 'react-dom', var: 'ReactDOM' }\n      ]\n    })\n  ]\n}\n```\n\n宿主传递共享模块的方式：\n\n```js\nimport remote from 'import-remote';\n\n// 通过await等待模块加载完毕\nconst testIndex = await remote('http://localhost:3000/test/index.js', {\n  // 共享模块也可以通过externals来传递\n  externals: { \n    react: require('react'), \n    'react-dom': require('react-dom'),\n  }\n});\n```\n\n#### 全局变量私有化\n\n通过`globalToScopes`选项可以将你的源代码中一些`window.xxx`、`global.xxx`的变量替换为一个同组模块共享的私有变量中。这在相互集成时全局变量冲突时的一种解决办法；\n\n如果你的webpack配置是这样的：\n\n```js\nconst ImportRemotePlugin = require('import-remote/plugin')\n\nmodule.exports = {\n  entry: {\n    index: 'index.js'\n  }\n  output: {\n    filename: '[name]-[chunkhash:5].js'\n  },\n  plugins: [\n    new ImportRemotePlugin({\n      globalToScopes: ['app', 'someVar']\n    })\n  ]\n}\n```\n\n则宿主在加载你的模块时，将会把你源代码中的`global.app`、`window.app`、`global.someVar`、`window.someVar`替换成`_wp_.g.app`、`_wp_.g.someVar`。\n\n注：全局变量私有化可能有风险，需要您仔细斟酌是否使用。毕竟最好的方案就是没有全局变量。该选项只是用于解决您目前无法或没时间去掉全局变量时的一种托底解决办法。\n\n## 运行期包使用说明\n\n### 远程加载方法\n\n函数签名：\n\n```ts\n/**\n * @param {string} url 远程模块的url地址\n * @param {object} options 加载选项\n * @param {object} options.externals 远程模块的依赖模块\n * @param {boolean} options.useEsModuleDefault 当远程模块导出的是ES模块时，是否只返回它的default导出部分\n * @returns {Promise\u003cany\u003e} 远程模块的导出内容\n **/\nfunction remote(url: string, options: { externals: { [key]: any } }): Promise\u003cany\u003e; \n```\n\n使用方法：\n\n```js\nimport remote from 'import-remote';\n\n// 通过await等待模块加载完毕\nconst testIndex = await remote('http://localhost:3000/test/index.js', {\n  // 配置模块需要依赖\n  externals: { \n    react: require('react'), \n    'react-dom': require('react-dom'),\n    'lodash': require('lodash'),\n  }\n});\n// 拿到模块输出对象后，即可做你想做的任何事了\ntestIndex.dosomething();\n```\n\n### 远程模块\n\n通过远程模块可以用于管理一个项目生成的所有模块：\n\n```js\nimport { RemoteModule } from 'import-remote';\n\n// 配置RemoteModule的host和依赖\nconst testModule = new RemoteModule('http://localhost:3000/test', {\n  externals: { \n    react: require('react'), \n    'react-dom': require('react-dom'),\n    'lodash': require('lodash'),\n  }\n});\n\n// 具体的加载路径为RemoteModule的`${host}${requireName}.js`\nconst testIndex = await testModule.require('index');\nconst testOther = await testModule.require('other');\n\ntestIndex.dosomething();\ntestOther.dosomething();\n```\n\n`RemoteModule`的的方法有：\n```ts\n{\n  /**\n   * @param {string} host 该项目生成的模块的基地址(host)\n   * @param {object} options 加载选项\n   * @param {object} options.externals 远程模块的依赖模块\n   * @param {boolean} options.useEsModuleDefault 当远程模块导出的是ES模块时，是否只返回它的default导出部分\n   * @returns {void}\n   **/\n  constructor(host: string, options: { externals: { [key]: any } }): void; \n  \n  /**\n   * 根据模块名生成该模块的入口地址\n   * @param {string} moduleName 模块名\n   * @returns {string} 该模块的入口地址\n   **/\n  resolveModuleUrl(moduleName: string = 'index'): string; \n\n  /**\n   * 发送HEAD请求判断`moduleName`是否存在，当存在时返回请求的响应头信息\n   * @param {string} moduleName 模块名\n   * @param {object} options 加载选项\n   * @returns {Promise\u003cobject|null\u003e} HEAD请求头信息或为空\n   **/\n  exist(moduleName: string = 'index', options: {}): Promise\u003cany\u003e; \n\n  /**\n   * 获取`moduleName`的meta信息\n   * @param {string} entryName 入口模块名\n   * @param {object} options 加载选项，和remote方法的option一致\n   * @returns {Promise\u003cany\u003e} 所有入口的描述文件\n   **/\n  requireEntries(entryName: string = 'index', options: {}): Promise\u003cany\u003e; \n\n  /**\n   * 获取`moduleName`的meta信息\n   * @param {string} moduleName 模块名\n   * @param {object} options 加载选项，和remote方法的option一致\n   * @returns {Promise\u003cany\u003e} 模块的meta信息\n   **/\n  requireMeta(moduleName: string = 'index', options: {}): Promise\u003cany\u003e; \n\n  /**\n   * 功能和requireMeta相同，只是将加载资源时的ajax设置为同步请求\n   * @param {string} moduleName 模块名\n   * @param {object} options 加载选项，和remote方法的option一致\n   * @returns {any} 远程模块的导出内容\n   **/\n  requireMetaSync(moduleName: string = 'index', options: {}): any; \n\n  /**\n   * 异步加载方法\n   * @param {string} moduleName 模块名，调用\n   * @param {object} options 加载选项，和remote方法的option一致\n   * @returns {Promise\u003cany\u003e} 远程模块的导出内容\n   **/\n  require(moduleName: string = 'index', options: {}): Promise\u003cany\u003e; \n\n  /**\n   * 功能和require相同，只是将加载资源时的ajax设置为同步请求\n   * @param {string} moduleName 模块名，调用\n   * @param {object} options 加载选项，和remote方法的option一致\n   * @returns {any} 远程模块的导出内容\n   **/\n  requireSync(moduleName: string = 'index', options: {}): any; \n\n  /**\n   * 异步加载方法,功能和require相同，只是在导出模块为es模块时，只导出它的default部分\n   * @param {string} moduleName 模块名，调用\n   * @param {object} options 加载选项，和remote方法的option一致\n   * @returns {Promise\u003cany\u003e} 远程模块的导出内容\n   **/\n  import(moduleName: string = 'index', options: {}): Promise\u003cany\u003e; \n\n  /**\n   * 功能和import相同，只是将加载资源时的ajax设置为同步请求\n   * @param {string} moduleName 模块名，调用\n   * @param {object} options 加载选项，和remote方法的option一致\n   * @returns {any} 远程模块的导出内容\n   **/\n  importSync(moduleName: string = 'index', options: {}): any;  \n}\n\n```\n\n### RemoteView\n\n`RemoteView`是一个`React`组件，模拟`iframe`，内部创建3个元素模拟`html`、`head`、`body`，通过`src`属性加载远程`React组件`, 通过该组件加载的资源会有自己独立的全局空间，移除该组件时，也将移除加载该远程模块时的所有资源。\n\n示例:\n```js\nimport React from 'react';\nimport RemoteView from 'import-remote/view';\n\nfunction Test(props) {\n  return \u003cdiv\u003e\n    \u003cRemoteView \n      src=\"http://localhost:3000/test.js\" \n      props={{\n        aa: 1,\n        bb: 2\n      }}\n      externals={{\n        'react': require('react'),\n        'react-dom': require('react-dom')\n      }}\n    /\u003e\n  \u003c/div\u003e;\n}\n```\n\n或者使用`RemoteModule`来加载:\n\n```js\nimport React from 'react';\nimport { RemoteModule } from 'import-remote';\nimport RemoteView from 'import-remote/view';\n\nconst testModule = new RemoteModule('http://localhost:3000/test', {\n  externals: { \n    react: require('react'), \n    'react-dom': require('react-dom'),\n    'lodash': require('lodash'),\n  }\n});\n\nfunction Test(props) {\n  return \u003cdiv\u003e\n    \u003cRemoteView \n      module={testModule}\n      moduleName=\"index\"\n      props={{\n        aa: 1,\n        bb: 2\n      }}\n    /\u003e\n  \u003c/div\u003e;\n}\n```\n\n`RemoteView`除了支持远程模块导出的`React`组件，也支持以下格式的组件导出接口：\n\n```js\n{\n  namespace?: string,\n  bootstrap: (props, children) =\u003e void,\n  mounted: (el, props) =\u003e primise|void,\n  update: (el, props, prevProps) =\u003e void,\n  unmount: (el) =\u003e void,\n}\n```\n\n和\n\n```js\n{\n  namespace?: string,\n  init: (props, options) =\u003e primise|void,\n  render: (el, props) =\u003e void,\n  destroy: (el) =\u003e void,\n}\n```\n\n注：如果`namespace`不为空，这将会将其添加到`body`模拟元素的`className`中。\n\n如果想将这样的对象转换成`React`组件，可以通过下面的办法：\n\n1. 直接将一个导出对象转换成`React`组件:\n\n```js\nimport { createAppView } from 'import-remote/view';\nimport testObject from './test-object';\n\nconst Test = createAppView(testObject);\n```\n\n\n2. 远程加载一个导出对象，并直接将其转换成`React`组件:\n\n```js\nimport { requireApp } from 'import-remote/view';\n\nconst Test = await requireApp('http://localhost:3000/test.js');\n```\n\n\n#### RemoteView的props\n\n- `scopeStyle: boolean` - 当为true，并且`shadow`为false时，将为引用的样式添加一个`hash`作用域，避免样式影响到外部。是一种在不支持`shadow DOM`的情况下解决样式冲突的一种解决办法\n\n- `scopePrefix: string = 'v-'` - 为引用样式创建的作用域名的前缀\n\n- `classPrefix: string = 'import-remote-'` - 创建的`html`、`head`、`body`模拟元素的类名前缀\n\n- `tag: string = 'div'` - 创建的`html`、`head`、`body`模拟元素的元素类型\n\n- `src: string` - 远程模块的入口文件地址\n\n- `module: RemoteModule` - 远程模块对象，和`moduleName`配合使用，与`src`属性互斥\n\n- `moduleName: string` - 远程模块名称，和`module`配合使用，与`src`属性互斥\n\n- `props: object` - 传递给远程模块导出组件的`props`\n  \n- `externals: object` - 远程组件的外部依赖\n\n- `shadow: boolean` - 是否将`html`、`head`、`body`创建在`shadow DOM`中\n   \n- `onViewLoading: (loading) =\u003e void` - 远程模块加载中的回调事件，分别会在加载前后调用\n\n- `onViewError: (error) =\u003e void` - 远程模块加载失败的回调事件\n\n- `hoc: Function` - 对导出组件的高阶封装，参数格式：`(Component: React.ComponentType | React.ForwardRefExoticComponent, error?: any) =\u003e React.ComponentType | React.ForwardRefExoticComponent`\n\n### RemoteApp\n\n`RemoteApp`是一个即插即用的React组件，当远程模块返回的结果本身就是React组件时，可以使用该组件加载对应的模块。它和`RemoteView`的区别是：`RemoteView`会局部化远程模块的作用域空间，而`RemoteApp`不会：\n\n```js\nimport React from 'react';\nimport { RemoteModule } from 'import-remote';\nimport { RemoteApp } from 'import-remote/view';\n// or \nimport { RemoteApp } from 'import-remote/view/app';\n \nconst testModule = new RemoteModule('http://localhost:3000/test', {\n  externals: { \n    react: require('react'), \n    'react-dom': require('react-dom'),\n    'lodash': require('lodash'),\n  }\n});\n\nfunction Test(props) {\n  return \u003cdiv\u003e\n    \u003cRemoteApp\n      module={testModule}\n      moduleName=\"index\"\n      aa=\"1\"\n      bb=\"2\"\n    /\u003e\n  \u003c/div\u003e;\n}\n```\n\n#### RemoteApp的props\n\n- `src: string` - 远程模块的入口文件地址\n\n- `module: RemoteModule` - 远程模块对象，和`moduleName`配合使用，与`src`属性互斥\n\n- `moduleName: string` - 远程模块名称，和`module`配合使用，与`src`属性互斥\n\n- `exportName: string` - 当远程模块的结果为一个`esModule`时，取`esModule`的导出`key`名，默认为`default`\n\n- `hoc: Function` - 对导出组件的高阶封装，参数格式：`(Component: React.ComponentType | React.ForwardRefExoticComponent, error?: any) =\u003e React.ComponentType | React.ForwardRefExoticComponent`\n\n- `clearWhenError: boolean` - 当加载远程组件失败时是否清除当前显示的组件，即上次加载的组件。默认为`true`。\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgxlmyacc%2Fimport-remote","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgxlmyacc%2Fimport-remote","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgxlmyacc%2Fimport-remote/lists"}