简体   繁体   中英

js modules usage in a multi-page web app (Closure compiler)

I have a web app that contains several pages with some js files of shared code.

- common1.js
- common2.js
- page1.js
- page2.js
- page3.js
...

The shared files are loaded with page1 and, on a button click, the page changes to page2 or page3. I use Closure Compiler and every page is a chunk.

--js "../common1.js" \
--chunk common1.min:1 \
--js "../common2.js" \
--chunk common2.min:1:common1.min \
--js "../page1.js" \
--chunk page1.min:1:common2.min \
--js "../page2.js" \
--chunk page2.min:1:common2.min \

All is working and the chunks are loaded correctly. (ADVANCED_OPTIMIZATIONS)

Unfortunately, I need to start using modules. I refactored the js files to use import/export. The problem is that all code is moved on my entry point and the other chunks are empty.

 --compilation_level ADVANCED_OPTIMIZATIONS \
 --language_out ECMASCRIPT_2021 \
 --dynamic_import_alias "dynamicImport" \
 --chunk_output_type "ES_MODULES" \

 --dependency_mode PRUNE_LEGACY \
 --entry_point "${JS_PATH}/page1.js" \

EG: page2 and page3 are empty.

What am I doing wrong? The only solution I've found is to build each page singularly. However, since many code is shared, the file output would be greater since the shared code cannot be used. (It is cached so there is no load time for it)

Each individual file is an individual entry point and you need to compile each of the files separately.

If they share common code, import them in their respective pages and compile the files separately.

If you need separate chunks with single entry point, try using the dynamic imports. This will create chunks as you expected.

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports

Note: Webpack handles dynamic chunks well enough. However I didn't tested this with Closure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM