{"id":13447886,"url":"https://github.com/ScriptedAlchemy/webpack-external-import","last_synced_at":"2025-03-22T01:31:33.611Z","repository":{"id":34635590,"uuid":"179774002","full_name":"ScriptedAlchemy/webpack-external-import","owner":"ScriptedAlchemy","description":"Dynamically import modules from other webpack bundles. Painless code sharing between separate apps","archived":false,"fork":false,"pushed_at":"2024-10-12T02:59:24.000Z","size":4856,"stargazers_count":415,"open_issues_count":68,"forks_count":42,"subscribers_count":12,"default_branch":"master","last_synced_at":"2024-10-29T15:48:37.873Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ScriptedAlchemy.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":"2019-04-06T01:00:26.000Z","updated_at":"2024-07-10T02:01:34.000Z","dependencies_parsed_at":"2023-01-15T08:15:51.395Z","dependency_job_id":"ecf8bde7-191c-412a-8da6-bb5e69dee753","html_url":"https://github.com/ScriptedAlchemy/webpack-external-import","commit_stats":{"total_commits":196,"total_committers":13,"mean_commits":"15.076923076923077","dds":0.2142857142857143,"last_synced_commit":"272b92a55de1e1669fa3770ced273fca16b17c41"},"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ScriptedAlchemy%2Fwebpack-external-import","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ScriptedAlchemy%2Fwebpack-external-import/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ScriptedAlchemy%2Fwebpack-external-import/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ScriptedAlchemy%2Fwebpack-external-import/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ScriptedAlchemy","download_url":"https://codeload.github.com/ScriptedAlchemy/webpack-external-import/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244893464,"owners_count":20527598,"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":[],"created_at":"2024-07-31T05:01:29.528Z","updated_at":"2025-03-22T01:31:33.287Z","avatar_url":"https://github.com/ScriptedAlchemy.png","language":"JavaScript","readme":"# Webpack External Import\n\n\u003e **import() other chunks and modules from third parties, or other webpack builds themselves! At runtime!**\n\n## This is now part of Webpack 5 - do not use external-import, read more here: http://module-federation.github.io/\n\n\u003cp align=\"center\"\u003e\n\n[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)\n  \u003ca href=\"https://www.npmjs.com/package/webpack-external-import\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/v/webpack-external-import.svg\" alt=\"Version\" /\u003e\n  \u003c/a\u003e\n\n  \u003ca href=\"https://www.npmjs.com/package/webpack-external-import\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/dt/webpack-external-import.svg\" alt=\"Downloads\" /\u003e\n  \u003c/a\u003e\n\n  \u003ca href=\"https://www.npmjs.com/package/webpack-external-import\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/dm/webpack-external-import.svg\" alt=\"License\" /\u003e\n  \u003c/a\u003e\n\n  \u003ca href=\"https://www.npmjs.com/package/webpack-external-import\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/l/webpack-external-import.svg\" alt=\"License\" /\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n \u003cimg src=\"docs/webpack-external-import.png\" width=\"40%\" alt=\"webpack-external-import\" /\u003e\n\u003c/p\u003e\n\n\u003e This project has been rewritten into the Webpack core. Its far more stable and available on npm webpack@5.0.0-beta.16 https://github.com/webpack/webpack/issues/10352\n\n\u003e ### ⚠️ This project no longer under development as been enhanced in the webpack 5 core ⚠️\n\u003e ### See the examples on module federation in webpack 5\n\n\\*\\*To jump to the _development_ section [click here](#development--debugging)\n\n# Installation\n\n### npm\n\n```sh\nnpm install webpack-external-import --save\n```\n\n### Yarn\n\n```sh\nyarn add webpack-external-import\n```\n\n### Version 2.0!\n\nMajor rewrite which has taken the original concept and built it directly into webpack runtime.\nA big achievement in this release is **tree-shaking support**\n\nIf you want to read me about what this tool does.\n\nRead the following:\n\n- https://link.medium.com/L5zHiwylI3\n- working on more use cases and writing about V2\n\n## Getting Started\n\n1.  Add `webpack-external-import/webpack` to your webpack plugins:\n\n```js\n// techblog.webpack.config.js\nconst URLImportPlugin = require(\"webpack-external-import/webpack\");\n{\n  plugins: [\n    new URLImportPlugin({\n      manifestName: \"website-one\"\n    })\n  ];\n}\n\n// otherblog.webpack.config\nconst URLImportPlugin = require(\"webpack-external-import/webpack\");\n{\n  plugins: [\n    new URLImportPlugin({\n      manifestName: \"website-two\"\n    })\n  ];\n}\n```\n\n2. If you are interleaving webpack bundles, load their manifests somewhere\n\n```js\n// index.js\nimport { corsImport } from \"webpack-external-import\";\nimport React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport App from \"./App.jsx\";\n\n// using Date.now() for cache busting the file. It should only less than 2kb\ncorsImport(`http://localhost:3002/importManifest.js?${Date.now()}`).then(() =\u003e {\n  ReactDOM.render(\u003cApp /\u003e, document.getElementById(\"app\"));\n});\n\n// you could also use native imports\n\nimport(\n  /* webpackIgnore:true */ `http://localhost:3002/importManifest.js?${Date.now()}`\n).then(() =\u003e {\n  ReactDOM.render(\u003cApp /\u003e, document.getElementById(\"app\"));\n});\n```\n\n## Usage\n\nThis plugin works with any Webpack driven application\n\n#### Vanilla JS\n\nThis assumes a import manifest was loaded somewhere else in the application already.\n\nIf you have not imported manifest then wrap your function in another promise:\n\n```js\ncorsImport(\"http://localhost:3002/importManifest.js\").then(() =\u003e {\n  someFunction();\n});\n```\n\nAs long as the `importManifest` was loaded - this is how it would be used\n`__webpack_require_.interleaved()` expects a module to contain both the module.id and the namespace\n\nThis allows external-import to know where to interleave from.\n`__webpack_require_.interleaved([namespace]/[module.id])`\n\nBelow is an example of interleaving a module from `website-2`\n\n```js\n// import a chunk from another website build with webpack-external-import\n\n__webpack_require__\n  .interleaved(\"website-2/ValidationRules\")\n  .then(validationRules =\u003e {\n    // proceed to use as a you would with a normal require statement\n    validationRules.validateObject(someObject);\n  });\n```\n\n### With JSX\n\n`ExternalComponent` exists for ease of use with React Components and is as SFC using React.Hooks\n\n```js\nimport { ExternalComponent } from \"webpack-external-import\";\nclass SomeComponent extends Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cExternalComponent\n          interleave={__webpack_require__.interleaved(\n            \"website-2/TitleComponent\"\n          )}\n          export=\"Title\"\n          title=\"Some Heading\"\n        /\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n## What is the use of `webpack-external-import` ?\n\n- **Load components over the wire** - Pull in components at runtime.\n- **Build leaner micro-frontends (MFE)** -\n  Micro-frontends can share bundle chunks and resources with each other while remaining self-contained, removing needless code duplication.\n- **Split a large, multi-team app into separate deployable chunks while keeping it as one SPA** - Large apps can be split into separate feature bundles that can be deployed independently, reducing deployment bottlenecks.\n- **Manage common js/vendor files automatically.** - Instead of dealing with peer dependencies, externals, or anything else, you can load the dependency from a remote source.\n- **LOSA Style frontend architecture** - Run multiple apps on a single page.\n- **FOSA Style frontend orchestration** - Powerful frontend orchestration, self-organizing application architecture. Many builds act as one\n\n### Advanced Setup - Injecting Webpack modules from another build\n\nUse the webpack plugin to inject webpack modules from another build into your build.\n\n_**Important**: Make sure manifestName_ is unique per webpack build.\nIf you have multiple builds, they all need to have a unique manifestName\n\n**webpack.config.js**\n\n```js\nconst URLImportPlugin = require(\"webpack-external-import/webpack\");\n{\n  plugins: [\n    new URLImportPlugin({\n      manifestName: \"website-one\"\n    })\n  ];\n}\n```\n\n## Mark Files for interleaving\n\nPretend we have two separate apps that each have their _independent_ build. We want to share a module from one of our apps with the other.\n\nTo do this, you must add an `interleave` object to `package.json`.\nThe `interleave` object tells the plugin to make the module accessible through a predictable name.\n\nFor example:\n\n```json\n// website-two package.json\n{\n  \"name\": \"some-package-name\",\n  \"interleave\": {\n    \"src/components/Title/index.js\": \"TitleComponent\",\n    \"src/components/hello-world/index.js\": \"SomeExternalModule\"\n  }\n}\n```\n\n```js\n// website-one App.js\n__webpack_require__\n  .interleaved(\"website-3/TitleComponentWithCSSFile\")\n  .then(TitleComponentWithCSSFile =\u003e \u003cTitleComponentWithCSSFile /\u003e);\n```\n\nThis ensures a easy way for other consumers, teams, engineers to look up what another project or team is willing\nto allow for interleaving\n\n## Working with Webpack Externals\n\nIt's important to follow the instructions below if you are planning to use Webpack externals.\nThis plugin must be installed on all builds - it is intended that the build creating providing external is built by this plugin.\nExternals work best in scenarios where the \"host\" app should supplying dependencies to an interleaved one.\n\n**Providing Externals**\nTo support webpack externals, you will need to use `provideExternals` to specify externals\n\n**Note:** you must use `provideExternals` **instead** of the webpack `externals` option.\n\n```js\nnew URLImportPlugin({\n  provideExternals: {\n    react: \"React\"\n  }\n});\n```\n\n**Consuming Externals**\nTo consume externals, you will need to use `useExternals` to inform webpack that the interleaved app should use the module specified by `provideExternals`\n\n```js\nnew URLImportPlugin({\n  useExternals: {\n    react: \"React\"\n  }\n});\n```\n\n## Full Example\n\n**WEBSITE-ONE**\n\n```js\n// app.js\n\nimport React, { Component } from \"react\";\nimport { ExternalComponent } from \"webpack-external-import\";\nimport HelloWorld from \"./components/goodbye-world\";\nimport \"react-select\";\n\nclass App extends Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      titleUrl: null,\n      manifestLoaded: false,\n      loaded: false\n    };\n  }\n\n  componentDidMount() {\n    __webpack_require__\n      .interleaved(\"website-3/TitleComponentWithCSSFile\")\n      .then(TitleComponentWithCSSFile =\u003e\n        console.log(TitleComponentWithCSSFile)\n      );\n  }\n\n  renderDynamic = () =\u003e {\n    const { loaded } = this.state;\n    if (!loaded) return null;\n    return __webpack_require__(\"SomeExternalModule\").default();\n  };\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cHelloWorld /\u003e\n\n        \u003cExternalComponent\n          interleave={__webpack_require__.interleaved(\n            \"website-2/TitleComponent\"\n          )}\n          export=\"Title\"\n          module=\"TitleComponent\"\n          title=\"Some Heading\"\n        /\u003e\n\n        \u003cExternalComponent\n          interleave={__webpack_require__.interleaved(\n            \"website-3/TitleComponentWithCSSFile\"\n          )}\n          export=\"Title\"\n          title=\"Title Component With CSS File Import\"\n        /\u003e\n        {this.renderDynamic()}\n      \u003c/div\u003e\n    );\n  }\n}\n\nPromise.all([\n  corsImport(`http://localhost:3002/importManifest.js?${Date.now()}`),\n  corsImport(`http://localhost:3003/importManifest.js?${Date.now()}`)\n]).then(() =\u003e {\n  ReactDOM.render(\u003cApp /\u003e, document.getElementById(\"app\"));\n});\n```\n\n**WEBSITE-TWO**\n\n```json\n// package.json\n\n{\n  \"name\": \"website-two\",\n  \"version\": \"0.0.0-development\",\n  \"author\": \"Zack Jackson \u003czack@ScriptedAlchemy.com\u003e (https://github.com/ScriptedAlchemy)\",\n  \"interleave\": {\n    \"src/components/Title/index.js\": \"TitleComponentWithCSSFile\",\n    \"src/components/Title/style.css\": \"TitleComponentWithCSSFileCSS\",\n    \"src/components/hello-world/index.js\": \"SomeExternalModule\"\n  }\n}\n```\n\n## API:\n\n```js\nmodule.exports = {\n  plugins: [\n    new URLImportPlugin({\n      manifestName: \"website-one\",\n      fileName: \"importManifest.js\",\n      basePath: ``,\n      publicPath: `//localhost:3001/`,\n      writeToFileEmit: false,\n      seed: null,\n      filter: null,\n      debug: true,\n      useExternals: {},\n      provideExternals: {}\n    })\n  ]\n};\n```\n\n### `options.fileName`\n\nType: `String`\u003cbr\u003e\nDefault: `importManifest.js`\n\nThe manifest filename in your output directory.\n\n### `options.publicPath`\n\nType: `String`\nDefault: `output.publicPath`\n\nA path prefix that will be added to values of the manifest.\n\n### `options.basePath`\n\nType: `String`\n\nA path prefix for all keys. Useful for including your output path in the manifest.\n\n### `options.writeToFileEmit`\n\nType: `Boolean`\u003cbr\u003e\nDefault: `false`\n\nIf set to `true` will emit to build folder and memory in combination with `webpack-dev-server`\n\n### `options.seed`\n\nType: `Object`\u003cbr\u003e\nDefault: `{}`\n\nA cache of key/value pairs to used to seed the manifest. This may include a set of [custom key/value](https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json) pairs to include in your manifest or may be used to combine manifests across compilations in [multi-compiler mode](https://github.com/webpack/webpack/tree/master/examples/multi-compiler). To combine manifests, pass a shared seed object to each compiler's ManifestPlugin instance.\n\n### `options.filter`\n\nType: `Function(FileDescriptor): Boolean`\n\n### `options.testPath`\n\nType: `Function(Object, FileDescriptor): Object`\u003cbr\u003e\nDefault: `src`\n\nTest resource path to see if plugin should apply transformations\n\n### `options.useExternals`\n\nType: `Object`\u003cbr\u003e\nDefault: `{}`\n\nInforms the webpack treat the following dependencies as externals.\nWorks the same way externals does.\n\n### `options.provideExternals`\n\nType: `Object`\u003cbr\u003e\nDefault: `{}`\n\nInforms webpack to provide the dependencies listed in the object to other apps using `useExternals`\n\n### **ExternalComponent**\n\nReact Component\n\n#### **Props**:\n\n**`src`: string** - a url to a javascript file, note it will need to be built by another webpack build running this plugin\n\n**`interleave`: function** - the `__webpack_require__.interleave()` function, which will return a module\n\n**`export`: string** - The named export to use as a component from the module being imported\n\n### The entry manifest\n\nEach webpack build using the webpack plugin emits a manifest file to the build output directory.\n\nThe manifest allows you to find a chunk that you want, even if the name has been hashed.\n\nBelow is an example of using the manifest.\n\nIn this file, I am importing code from another website/build. My application is loading website two's manifest, which is automatically added to `window.entryManifest` under the `manifestName` I set in the webpack plugin. After that, I'm importing a chunk from website-two, in this case - the chunk is code-split.\n\n```js\ncomponentDidMount() {\n  corsImport('http://localhost:3002/importManifest.js').then(() =\u003e {\n      const Title = __webpack_require__\n        .interleaved(\"website-two/TitleComponent\")\n\n        Title.then(console.log) // =\u003e Module {default: ()=\u003e{}, Title: ()=\u003e{}}\n  });\n}\n```\n\n## DEMO\n\nHow to start using the demo\nIn the _root directory_, run the following\n\n1. run `yarn install`\n2. run `yarn demo` from the root directory\n3. browse to [localhost:3001](http://localhost:3001) and you will see components from two other websites\n\nThis command will install, all dependencies, build the source for the plugin, install the demo dependencies, run all builds and start serving\n\n## Development \u0026 Debugging\n\nHow to start the demo in debug mode, using node --inspect and connecting to a chrome debugger\n\n\u003e This is mainly for debugging the webpack plugin\n\nIn the root directory, run the following\n\n1. `yarn install`\n2. `yarn demo:debug` from the root directory\n3. browse to [localhost:3001](http://localhost:3001)\n\n**Note:** _[localhost:3001](http://localhost:3001) is the \"consumer app, while the other is the provider app\". Both apps work independently and you should check both of them out (they are extremely basic)_\n\nOpen chrome dev tools and you should see the box highlighted below appear, click on it to connect to the webpack debugger\n![GitHub Logo](/docs/inspect.png)\n\n### Logging\n\nThe default compilation removes console log statements via `babel-plugin-transform-remove-console`, which is run when `BABEL_ENV=production` (default). To compile a version with logging enabled, run `yarn compile` directly.\n","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FScriptedAlchemy%2Fwebpack-external-import","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FScriptedAlchemy%2Fwebpack-external-import","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FScriptedAlchemy%2Fwebpack-external-import/lists"}