• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Lazy Import
2
3As applications evolve with more features, the time required for cold start increases significantly. The main reason is that a large number of modules are loaded at the early stage of startup, and many of them are redundant and not actually executed. This not only prolongs application initialization but also leads to invalid resource utilization. To address this, it is crucial to streamline the loading process by eliminating non-essential file executions to optimize cold start performance and ensure a smooth user experience.
4
5> **NOTE**
6>
7> - The lazy import feature is supported since API version 12.
8>
9> - To use the lazy import syntax on API version 12, you must configure **"compatibleSdkVersionStage": "beta3"** in the project. Otherwise, the compilation fails. For details, see [Project-level build-profile.json5 File](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-hvigor-build-profile-V5#section511142752919).
10
11
12## Features
13
14The lazy import feature allows files that are pending loading to remain unloaded during the cold start phase. Instead, these files are loaded synchronously on-demand only when the application actually needs them during runtime, thereby reducing the time required for application cold start.
15
16## Usage
17
18You can use <!--Del-->[<!--DelEnd-->Trace<!--Del-->](../performance/common-trace-using-instructions.md)<!--DelEnd--> or logs to identify files that are not actually called during cold start.<!--RP1--> For details about the analysis method, see [Lazy Import](../performance/Lazy-Import-Instructions.md).<!--RP1End--> By analyzing the data, you can accurately identify the files that do not need to be pre-loaded in the startup phase, and add the **lazy** flag for the call points of these files. Note that the subsequent loading is synchronous and may block task execution. (For example, if a click task triggers a lazy import, the runtime will execute the files not loaded during the cold start, thereby increasing latency.) Therefore, you need to evaluate whether to use the **lazy** flag.
19
20> **NOTE**
21>
22> You are not advised to blindly add **lazy** flags, as this can also increase the overhead of identification during compilation and runtime.
23
24## Scenario Behavior Analysis
25
26- Use lazy-import for deferred loading.
27
28    ```typescript
29        // main.ets
30        import lazy { a } from "./mod1";    // "mod1" is not executed.
31        import { c } from "./mod2";         // "mod2" is executed.
32
33        // ...
34
35        console.info("main executed");
36        while (false) {
37            let xx = a;
38        }
39
40        // mod1.ets
41        export let a = "mod1 executed"
42        console.info(a);
43
44        // mod2.ets
45        export let c = "mod2 executed"
46        console.info(c);
47
48    ```
49
50    The execution result is as follows:
51
52    ```typescript
53        mod2 executed
54        main executed
55    ```
56
57- Use both lazy-import and native import for the same module.
58
59    ```typescript
60        // main.ets
61        import lazy { a } from "./mod1";    // "mod1" is not executed.
62        import { c } from "./mod2";         // "mod2" is executed.
63        import { b } from "./mod1";         // "mod1" is executed.
64
65        // ...
66
67        console.info("main executed");
68        while (false) {
69            let xx = a;
70        }
71
72        // mod1.ets
73        export let a = "mod1 a executed"
74        console.info(a);
75
76        export let b = "mod1 b executed"
77        console.info(b);
78
79        // mod2.ets
80        export let c = "mod2 c executed"
81        console.info(c);
82
83    ```
84
85    The execution result is as follows:
86
87    ```typescript
88        mod2 c executed
89        mod1 a executed
90        mod1 b executed
91        main executed
92    ```
93
94    If the keyword **lazy** is deleted from the **main.ets** file, the execution sequence is as follows:
95
96    ```typescript
97        mod1 a executed
98        mod1 b executed
99        mod2 c executed
100        main executed
101    ```
102
103## Syntax Specifications and Supported Versions
104
105- The lazy import feature supports the following syntax:
106
107| Syntax                                           | ModuleRequest  | ImportName | LocalName   | Supported API Version|
108|:----------------------------------------------|:---------------|:-----------|:------------|:-----------|
109| import lazy { x } from "mod";                 | "mod"          | "x"        | "x"         | API 12      |
110| import lazy { x as v } from "mod";            | "mod"          | "x"        | "v"         | API 12      |
111| import lazy x from "mod";                     | "mod"          | "default"  | "x"         | API 18      |
112| import lazy { KitClass } from "@kit.SomeKit"; | "@kit.SomeKit" | "KitClass" | "KitClass"  | API 18      |
113
114- Lazy importing of shared modules or modules within a dependency path that includes shared modules
115    Lazy import remains effective for shared modules. For details about the constraints, see [Shared Module](../arkts-utils/arkts-sendable-module.md).
116
117### Incorrect Example
118
119The following syntax will cause compilation errors:
120
121```typescript
122    export lazy var v;                    // The compiler reports an application compilation error.
123    export lazy default function f(){};   // The compiler reports an application compilation error.
124    export lazy default function(){};     // The compiler reports an application compilation error.
125    export lazy default 42;               // The compiler reports an application compilation error.
126    export lazy { x };                    // The compiler reports an application compilation error.
127    export lazy { x as v };               // The compiler reports an application compilation error.
128    export lazy { x } from "mod";         // The compiler reports an application compilation error.
129    export lazy { x as v } from "mod";    // The compiler reports an application compilation error.
130    export lazy * from "mod";             // The compiler reports an application compilation error.
131
132    import lazy * as ns from "mod";            // The compiler reports an application compilation error.
133    import lazy KitClass from "@kit.SomeKit"   // The compiler reports an application compilation error.
134    impott lazy * as MyKit from "@kit.SomeKit" // The compiler reports an application compilation error.
135```
136
137If the **type** keyword is added to the syntax, an error is reported.
138
139```typescript
140    import lazy type { obj } from "./mod";    // Not supported. The compiler reports an application compilation error.
141    import type lazy { obj } from "./mod";    // Not supported. The compiler reports an application compilation error.
142
143```
144
145### Syntax Not Recommended
146
147- Incomplete **lazy** flags within the same .ets file
148
149    Incomplete marking will cause lazy imports to fail and increase the overhead of identifying lazy-imported modules.
150    ```typescript
151        // main.ets
152        import lazy { a } from "./mod1";    // Obtain the object a from "mod1" and add the lazy flag.
153        import { c } from "./mod2";
154        import { b } from "./mod1";         // Obtain the attributes in "mod1". This syntax is not added with the lazy flag, so "mod1" is executed by default.
155
156        // ...
157    ```
158- Re-exporting lazy-imported variables within the same .ets file without using them
159
160    The variable **c** is not used in **B.ets**, so **B.ets** does not trigger execution. When **c** is used in **A.ets**, it is not initialized, resulting in a JS exception.
161    ```typescript
162        // A.ets
163        import { c } from "./B";
164        console.info(c);
165
166        // B.ets
167        import lazy { c } from "./C";    // Obtain the object c from "C" and add the lazy flag.
168        export { c }
169
170        // C.ets
171        let c = "c";
172        export { c }
173    ```
174    Result:
175    ```typescript
176        ReferenceError: c is not initaliized
177             at func_main_0 (A.ets:2:13)
178    ```
179
180    ```typescript
181        // A_ns.ets
182        import * as ns from "./B";
183        console.info(ns.c);
184
185        // B.ets
186        import lazy { c } from "./C";    // Obtain the object c from "C" and add the lazy flag.
187        export { c }
188
189        // C.ets
190        let c = "c";
191        export { c }
192    ```
193    Result:
194    ```typescript
195    ReferenceError: module environment is undefined
196        at func_main_0 (A_ns.js:2:13)
197    ```
198
199- You need to evaluate the impact of lazy imports.
200    * Side effects that are independent of the module's execution (such as initializing global variables and mounting **globalThis**). For details, see [Side Effects and Optimization of Module Loading](./arkts-module-side-effects.md).
201    * Negative impact on the functionality of features due to the delay caused by triggering lazy imports when using exported objects.
202    * Bugs caused by modules not being executed due to the use of the lazy import feature.
203
204 <!--no_check-->