This project demonstrates running two distinct, localized Angular element bundles in the same page using @angular-builders/custom-webpack. For simplicity of implementation, they look the same, but they are two distinct sources and builds.
A live demo is available at https://trevorkarjanis.github.io/angular-multiple-bundles.
Run npm run build
to build the project.
Run npm start
to start a development server at http://127.0.0.1:8080.
- Install @angular-builders/custom-webpack.
npm install --save-dev @angular-builders/custom-webpack
- Configure the builder and custom webpack configuration for each project in angular.json.
"app-element": {
"projectType": "application",
...
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "projects/<project name>/webpack.config.js",
"mergeStrategies": {
"externals": "replace"
}
}
}
-
Create a custom webpack configuration file, webpack.config.js, in each project directory.
-
In each custom webpack configuration, define unique values for the jsonpFunction and library output configuration options (example).
module.exports = {
output: {
jsonpFunction: 'webpackJsonp<project name>',
library: '<project name>'
}
}
-
Build the project.
-
Include each project's runtime, styles, and main bundles in the correct order in the target page. Include the polyfills bundle only once (example).
<script src="app-element/runtime.js" defer></script>
<script src="app-element/polyfills.js" defer></script>
<script src="app-element/styles.js" defer></script>
<script src="app-element/main.js" defer></script>
<script src="app-element-2/runtime.js" defer></script>
<script src="app-element-2/styles.js" defer></script>
<script src="app-element-2/main.js" defer></script>
This project demonstrates running multiple elements with separate Angular runtimes. It is preferred, however, to include multiple elements in one bundle that utilizes a single instance of the framework and unique chunks. In some cases, it may be reasonable to distribute all elements in a single bundle built from a selfcontained, unbootstrapped "application" build. Optimally, the components would be distributed in an Angular library and either defined as custom elements in independent modules or bundled per consuming application.