| 93 | } |
| 94 | |
| 95 | function lazyRequirePlugin(opts: BuildOptions, moduleIds: string[]): Plugin { |
| 96 | return { |
| 97 | name: 'lazyRequirePlugin', |
| 98 | setup(build) { |
| 99 | build.onEnd(async (buildResult) => { |
| 100 | const bundle = getFirstOutputFile(buildResult); |
| 101 | let code = Buffer.from(bundle.contents).toString(); |
| 102 | |
| 103 | for (const moduleId of moduleIds) { |
| 104 | const str = `require("${moduleId}")`; |
| 105 | while (code.includes(str)) { |
| 106 | code = code.replace(str, `_lazyRequire("${moduleId}")`); |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | code = code.replace(`"use strict";`, `"use strict";\n\n${getLazyRequireFn(opts)}`); |
| 111 | return fs.writeFile(bundle.path, code); |
| 112 | }); |
| 113 | }, |
| 114 | }; |
| 115 | } |
| 116 | |
| 117 | /** |
| 118 | * To avoid having user to install puppeteer for building their app (even if |