$ npm install webpack-external-import
import() URLs and other external resources from third parties, or other webpack builds themselves!
$ yarn webpack-external-import
This project is under active development
**To jump to the development section click here
npm install webpack-external-import --save
yarn add webpack-external-import --save
webpack-external-import/webpack to your webpack plugins:// techblog.webpack.config.js
const URLImportPlugin = require('webpack-external-import/webpack')
{
plugins: [
new URLImportPlugin({
manifestName: 'website-one'
})
]
}
import() polyfill (recommended)// index.js
import 'webpack-external-import/polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
import {corsImport} from "webpack-external-import"
// if importing on the same domain and CORS isnt an issue
import(/* webpackIgnore:true */'http://localhost:3002/importManifest.js')
// if you need to import from a third party where CORS is an issue
corsImport('http://localhost:3002/importManifest.js')
import() with a polyfill to act as a script loader. We also have a fallback script loader for loading CORS.// App.jsx
// import a chunk from another website build with webpack-external-import
import {corsImport} from "webpack-external-import"
componentDidMount() {
corsImport('http://localhost:3002/importManifest.js').then(() => {
this.setState({ manifestLoaded: true });
importDependenciesOf('http://localhost:3002', 'website-two', 'TitleComponent').then((url) => {
this.setState({ titleUrl: url });
});
// if CORS isnt a problem, you can use native import (its polyfilled)
import(/* webpackIgnore:true */getChunkPath('http://localhost:3002', 'website-two', 'SomeExternalModule.js')).then(() => {
console.log('got module, will render it in 2 seconds');
setTimeout(() => {
this.setState({ loaded: true });
}, 2000);
});
});
}
Or with JSX and a react component
import {ExternalComponent, getChunkPath} from 'webpack-external-import'
render() {
const { manifestLoaded } = this.state;
return (
<div>
<HelloWorld />
{ manifestLoaded && <ExternalComponent src={getChunkPath('http://localhost:3002', 'website-two', 'TitleComponent.js')} module="TitleComponent" export="Title" title="Some Heading" />}
</div>
);
}
webpack-external-import ?Use the webpack plugin to inject webpack modules from another build into your build.
Important: Make sure manifestName is unique per webpack build. If you have multiple builds, they all need to have a unique manifestName
webpack.config.js
const URLImportPlugin = require('webpack-external-import/webpack')
{
plugins: [
new URLImportPlugin({
manifestName: 'website-one'
})
]
}
Pretend 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.
To do this, we add an externalize comment to the module. The Externalize magic comment tells the plugin to make the module available externally with the name ExampleModule:
| Application A | Application B | |||
|---|---|---|---|---|
| Provider: Javascript Asset |
|
|||
|
Provider: Code-Splits asset into title-cnk |
empty | empty | ||
| Consumer File |
|
|||
| React Example |
|
Pretend we have two separate apps that each have their own independent build. We want to share a module from one of our apps with the other.
To do this, we add an externalize comment to the module. This tells the plugin to make the module available externally with the name ExampleModule and webpack will chunk this file into dist/ExampleModule.js
// Title.js
import React from 'react';
export const Title = ({title}) => {
return (<h1>{title}</h1>)
}
export const alert = (message) => {
alert(message)
}
/*externalize:ExampleModule*/
The ExampleModule can now be pulled into our other app using import:
import(/* webpackIgnore:true */'http://website1.com/js/ExampleModule.js').then(({ExampleModule})=>{
ExampleModule.alert('custom alert')
});
There is also a React component, ExternalComponent, that can be useful for importing React components:
import {ExternalComponent} from 'webpack-external-import'
()=>{
return (
<ExternalComponent src={helloWorldUrl} module="ExampleModule" export='Title' title={'Some Heading'} cors/>
)
}
// WEBSITE-ONE
//app.js
import React, {Component} from 'react';
import {hot} from 'react-hot-loader';
import HelloWorld from './components/hello-world';
import {ExternalComponent,corsImport} from 'webpack-external-import'
class App extends Component {
constructor(props) {
super(props);
this.state = {
titleUrl: null,
manifestLoaded: false,
loaded: false,
};
}
componentDidMount() {
corsImport('http://localhost:3002/importManifest.js').then(() => {
this.setState({ manifestLoaded: true });
importDependenciesOf('http://localhost:3002', 'website-two', 'TitleComponent').then((url) => {
this.setState({ titleUrl: url });
});
import(/* webpackIgnore:true */getChunkPath('http://localhost:3002', 'website-two', 'SomeExternalModule.js')).then(() => {
console.log('got module, will render it in 2 seconds');
setTimeout(() => {
this.setState({ loaded: true });
}, 2000);
});
});
}
renderDynamic = () => {
const { loaded } = this.state;
if (!loaded) return null;
return __webpack_require__('SomeExternalModule').default();
}
render() {
const { manifestLoaded, titleUrl } = this.state;
if (!manifestLoaded) {
return 'Loading...';
}
return (
<div>
<HelloWorld />
{titleUrl && <ExternalComponent src={titleUrl} module="TitleComponent" export="Title" title="Some Heading" />}
{this.renderDynamic()}
</div>
);
}
}
export default App
//WEBSITE-TWO
//App.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
component: null
};
}
componentDidMount() {
import('./components/hello-world').then((HelloWorld) => {
this.setState({component: HelloWorld.default})
})
}
render() {
if (!this.state.component) return <div/>
const {component: HelloWorld} = this.state
return <HelloWorld title="Hello from React webpack"/>;
}
}
export default hot(module)(App);
// Title.js
import React from 'react';
export const Title = ({title}) => {
return (<h1>{title}</h1>)
}
/*externalize:TitleComponent*/
// webpack.config.js
module.exports = {
output: {
publicPath
},
plugins: [
new URLImportPlugin(options)
]
}
options.fileNameType: String
Default: manifest.json
The manifest filename in your output directory.
options.publicPathType: String
Default: output.publicPath
A path prefix that will be added to values of the manifest.
options.basePathType: String
A path prefix for all keys. Useful for including your output path in the manifest.
options.writeToFileEmitType: Boolean
Default: false
If set to true will emit to build folder and memory in combination with webpack-dev-server
options.seedType: Object
Default: {}
A cache of key/value pairs to used to seed the manifest. This may include a set of custom key/value pairs to include in your manifest or may be used to combine manifests across compilations in multi-compiler mode. To combine manifests, pass a shared seed object to each compiler's ManifestPlugin instance.
options.filterType: Function(FileDescriptor): Boolean
Filter out files. FileDescriptor typings
options.testType: Function(Object, FileDescriptor): Object
Default: src
Test resource path to see if plugin should apply transformations
options.mapType: Function(FileDescriptor): FileDescriptor
Modify files details before the manifest is created. FileDescriptor typings
options.sortType: Function(FileDescriptor): number
Sort files before they are passed to generate. FileDescriptor typings
options.generateType: Function(Object, FileDescriptor): Object
Default: (seed, files) => files.reduce((manifest, {name, path}) => ({...manifest, [name]: path}), seed)
Create the manifest. It can return anything as long as it's serializable by JSON.stringify. FileDescriptor typings
options.serializeType: Function(Object): string
Default: (manifest) => JSON.stringify(manifest, null, 2)
Output manifest file in a different format then json (i.e., yaml).
React Component
src: string - Import source URL
module: string - Module name, must match what was declared using /externalize:ExampleModule/
export: string - The named export to use as a component from the module being imported
cors: bool - If asset is being loaded from a url which throws a CORS error. This will inject a script to the browser
<ExternalComponent src={helloWorldUrl} module="ExampleModule" export='Title' title={'Some Heading'}/>
FileDescriptor {
path: string;
name: string | null;
isInitial: boolean;
isChunk: boolean;
chunk?: Chunk;
isAsset: boolean;
isModuleAsset: boolean;
}
Each webpack build using the webpack plugin emits a manifest file to the build output directory.
The manifest allows you to find a chunk that you want, even if the name has been hashed.
Below is an example of using the manifest.
In 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.
componentDidMount() {
corsImport('http://localhost:3002/importManifest.js').then(() => {
this.setState({ manifestLoaded: true });
importDependenciesOf('http://localhost:3002', 'website-two', 'TitleComponent').then((url) => {
this.setState({ titleUrl: url });
});
import(/* webpackIgnore:true */getChunkPath('http://localhost:3002', 'website-two', 'SomeExternalModule.js')).then(() => {
console.log('got module, will render it in 2 seconds');
setTimeout(() => {
this.setState({ loaded: true });
}, 2000);
});
});
}
How to start using the demo In the root directory, run the following
yarn installyarn demo from the root directoryThis command will install, all dependencies, build the source for the plugin, install the demo dependencies, run all builds and start serving
How to start the demo in debug mode, using node --inspect and connecting to a chrome debugger
This is mainly for debugging the webpack plugin
In the root directory, run the following
yarn installyarn demo:debug from the root directoryNote: 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)
Open chrome dev tools and you should see the box highlighted below appear, click on it to connect to the webpack debugger

© 2010 - cnpmjs.org x YWFE | Home | YWFE