Dynamic import expressions are a new feature and part of ECMAScript that allows users to asynchronously request a module at any arbitrary point in your program. TC39 JavaScript committee has it’s own proposal which is in stage 3, and it’s called import() proposal for JavaScript.
However we knew that when the vendor.js files size is high, then the loading time also will get increased. So to resolve this, Angular webpack bundler has a feature called Code Splitting which will help us to split the code into Multiple chunk files.
With the help of dynamic import(). We can avoid the unnecessary files even when the application initially loads.
After this, i had a quick discussion with our web development team and decided to implement this feature in our Angular projects and the result is amazed us! yes it’s great. So without limiting this i came forward to share it with you guys.
So let’s look into this with an example.
TypeScript 2.4 and above versions have this dynamic import expression which will automatically split your JS final optimization bundle into multiple chunks.
Initial configuration
Initially the code will look like below,
Dynamic import() depend on the tsconfig.json. "compilerOptions": { "outDir": "../out-tsc/app", "module": "es2015", "types": [] },
To change the configuration
Replace the module “es2015” to “esnext” . Now, TypeScript produces the mimic impot() statement which will be the input for Webpack Code Splitting. Once the modification is done, then the code will like this,
"compilerOptions": { "outDir": "../out-tsc/app", "module": "esnext", "types": [] }
Import moment js library in the angular application.
Basically when you try to include the momentjs library, then our final optimization bundle size will get high due to it’s added options like multiple languages and locate options.
So the better approach to avoid this conflict would be uploading the libraries only when the particular module is required. Here.s where the dynamic import()
expressions takes place.
Follow the below code for dynamic import
import(/* webpackChunkName: "chunkName" */ 'library') .then(('library') => { // your code here console.log( Dynamic Import Expression:'); }) .catch((err) => { // show error code here console.log('Failed to load library); });
Now, will tell you how to add the moment.js library here. To include the moment.js library type the below command,
npm install moment
[ctt template=”5″ link=”lUZB8″ via=”no” ]Also you can read: Tips To Optimize Angular Application To Increase The Website Speed[/ctt]
Next, you can see how i have changed the above code by including moment.js library,
import(/* webpackChunkName: "momentjs" */ 'moment') .then((moment) => { const time = (moment as any).default().format(); console.log(time); }) .catch((err) => { console.log('Failed to load moment', err); });
We can also have the button to dynamically import the moment.js library whenever it’s required. For that, we need to call the function as below in app.html files,
<button mat-raised-button color="primary" (click)="onImport()">Dynamic import </button> onImport(){ // Your import library code here }
Our Result :
So the “moment chunk file” will be loaded the moment you click on the button, we can check it through the network tab in the inspector console as you can see below,
Import Dynamic Module
Now, hope I had cleared you to add the third party library manually. Next, will see how to import the .ts file dynamically.
import(/* webpackChunkName: "stringHelpers" */ './string-helpers').then(module => { Const .name = module.reverseString(‘string name’); console.log(‘Reverae string’, name); });
String-helpers is .ts files. This file will dynamically include the ts files based on the requirements. The above code will call reverseString functions.
string-helpers.ts have collection of function. This functions can be exported to reverseString in following way,
export function reverseString(input: string) { return input.split('').reverse().join(''); }
[ctt template=”5″ link=”56xzd” via=”no” ]Related: Tips To Optimize Angular Application To Increase The Website Speed[/ctt]
Let’s see how the button action will get the reverse string,
<button mat-raised-button color="primary" (click)="onRecerse()">Dynamic import </button> onRecerse(){ //Your import module code here }
Result:
The final build will have all the split chunk files as you can see it on the below screen,
Ufffff! it sounds perfect! yes we did it guys! Hope you will find it helpful!, What more? give it out a try and let us know your opinions. Also if you have any queries in resolving this then drop a comment. We would definitely try to help you out.
Mad over reading? Then never miss out anything from our blog works where you can read about all latest technologies & it’s updates which would be perfect for your 15 minutes tea break! What else guys hit the subscribe link and go crazy over learning. If you are looking for angular developers for your project ? Hire Angular developer from Agira Technologies to build best web-apps at affordable rates. Our dedicated Angular developers are well-versed with all the updates and ensure top-notch web applications development to meet your business requirements. For any queries reach us via info@agiratech.com