How to decrease prod bundle size?

后端 未结 14 1374
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

提交回复
热议问题