Angular 9如何通过ng build生成单份JS文件?适配微前端架构
Got it, let's tackle this problem—you're working with an Angular 9 app built via Angular CLI, which spits out separate ES5 and ES2015 bundles (like main-es5.js and main-es2015.js) thanks to differential loading. But for your microfrontend setup, you need a single JS file to upload. Here are two solid approaches to make this happen:
Differential Loading is Angular's built-in mechanism for generating multiple bundles to support different browser versions. Turning it off will make the CLI output only one version of your bundle directly.
- Open your project's root
angular.jsonfile - Locate the
architect > build > optionsblock for your target project - Add these two configuration entries:
"target": "es5", // Or use "es2015" if you only need modern browser support "differentialLoading": false - Save the file, then re-run your build command:
ng build --prod # Use --prod for production builds - Now your
distfolder will only contain a singlemain.jsfile, no extra merging needed.
Note: Choosing es5 ensures maximum browser compatibility but results in a larger file size. Opting for es2015 gives you a smaller bundle but only works with modern browsers—pick based on your compatibility needs.
If you must support both legacy and modern browsers but still need a single file, you can use a bundler like Rollup to combine the existing ES5/ES2015 bundles into one cross-compatible file:
- First, run your normal build to generate all bundles:
ng build --prod - Install Rollup and required plugins:
npm install rollup @rollup/plugin-node-resolve @rollup/plugin-commonjs --save-dev - Create a
rollup.config.jsfile in your project root (replaceyour-project-namewith your actual project folder name indist):import resolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; export default { input: [ 'dist/your-project-name/runtime-es5.js', 'dist/your-project-name/polyfills-es5.js', 'dist/your-project-name/main-es5.js' // Add ES2015 files here if you want to merge both versions for full compatibility ], output: { file: 'dist/your-project-name/main-bundled.js', format: 'iife', // Ideal for exposing your microfrontend as a global variable name: 'MyAngularMicroFrontend' // Custom global variable name for the host app to access }, plugins: [resolve(), commonjs()] }; - Run Rollup to merge the files:
npx rollup -c rollup.config.js - You'll find the merged single file
main-bundled.jsin yourdistfolder ready for upload.
Note: Merging both ES5 and ES2015 versions will create a fully compatible but larger bundle. Don't forget to include critical files like runtime and polyfills in the merge—without them, your app won't run correctly.
内容的提问来源于stack exchange,提问作者Anand Kumar

