如何通过Angular CLI生成ES5与ES6双版本站点?
Hey there! Great question—this is exactly the kind of optimization that can make a big difference for modern browser users while keeping support for older ones. The good news is that Angular CLI has built-in support for this exact scenario via what's called differential loading, and it's been available since Angular 8. Here's how it works and how you can leverage it:
How Differential Loading Solves This
Differential loading automatically generates two sets of bundles when you build your app:
- An ES2015+ (ES6+) bundle for modern browsers that support modules
- An ES5 bundle for older browsers that don't
The CLI then adds smart script tags to your index.html that let browsers self-select the right bundle:
Modern browsers will load the ES6+ bundle via
<script type="module">(which is smaller and faster to parse/execute), while older browsers fall back to the ES5 bundle via<script nomodule>.
Enabling & Configuring It
You don't need any third-party tools—this is baked into Angular CLI by default. To customize the browser targets:
Update your
browserslistfile (in your project root) to define which browsers get the ES5 bundle vs the ES6+ bundle. For example:# Modern browsers (ES6+) last 2 Chrome versions last 2 Firefox versions last 2 Safari versions last 2 Edge versions # Legacy browsers (ES5) IE 11Verify your
angular.jsonbuild configuration—ensure thetargetis set toes2015(this is the default for new Angular projects):"build": { "builder": "@angular-devkit/build-angular:browser", "options": { "target": "es2015", // ... other options } }Build your app with
ng build --prod(or justng buildfor development). The CLI will output both bundles in thedistfolder, and yourindex.htmlwill include the conditional script tags automatically.
If You Need Separate Deployments
If you want to host the ES6+ and ES5 versions as completely separate sites (instead of using differential loading's auto-selection), you can set up multiple build configurations in angular.json:
Add a
legacyconfiguration targeting ES5:"configurations": { "production": { "target": "es2015", "browserslist": [ "last 2 Chrome versions", "last 2 Firefox versions", "last 2 Safari versions", "last 2 Edge versions" ] }, "legacy": { "target": "es5", "browserslist": [ "IE 11", "last 4 Chrome versions", "last 4 Firefox versions" ] } }Build each version separately:
ng build --configuration production # ES6+ bundle ng build --configuration legacy # ES5 bundle
Has This Been Implemented?
Absolutely—differential loading is a standard feature used by thousands of Angular apps. It's the official Angular way to optimize modern browser performance while maintaining legacy support, so you don't need to reinvent the wheel here.
内容的提问来源于stack exchange,提问作者Sergey

