How to decrease prod bundle size?

后端 未结 14 1343
Happy的楠姐
Happy的楠姐 2020-11-28 01:31

I have a simple app, initialized by angular-cli.

It display some pages relative to 3 routes. I have 3 components. On one of this page I use lodash

相关标签:
14条回答
  • 2020-11-28 02:03

    The following solution assumes you are serving your dist/ folder using nodejs. Please use the following app.js in root level

    const express = require('express'),http = require('http'),path = require('path'),compression = require('compression');
    
    const app = express();
    
    app.use(express.static(path.join(__dirname, 'dist')));
    app.use(compression()) //compressing dist folder 
    app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname, 'dist/index.html'));
    })
    
    const port = process.env.PORT || '4201';
    app.set('port', port);
    
    const server = http.createServer(app);
    server.listen(port, () => console.log('Running at port ' + port))
    

    Make sure you install dependencies;

    npm install compression --save
    npm install express --save;
    

    Now build the app

    ng build --prod --build-optimizer
    

    If you want to further compress the build say reduce 300kb(approx) from , then follow the below process;

    Create a folder called vendor inside the src folder and inside vendor folder create a file rxjs.ts and paste the below code in it;

    export {Subject} from 'rxjs/Subject';
    export {Observable} from 'rxjs/Observable';
    export {Subscription} from 'rxjs/Subscription';
    

    And then add the follwing in the tsconfig.json file in your angular-cli application. Then in the compilerOptions , add the following json;

    "paths": {
          "rxjs": [
            "./vendor/rxjs.ts"
          ]
        }
    

    This will make your build size way too smaller. In my project I reduced the size from 11mb to 1mb. Hope it helps

    0 讨论(0)
  • 2020-11-28 02:05

    Check you have configuration named "production" for ng build --prod, since it is shorthand for ng build --configuration=production No answer solved my problem, because the problem was sitting right in front of the screen. I think this might be quite common... I've internationalized the app with i18n renaming all configurations to e.g. production-en. Then I built with ng build --prod assuming, that the default optimization is used and should be close to optimal, but in fact just ng build has been executed resulting in 7mb bundle instead of 250kb.

    0 讨论(0)
提交回复
热议问题