简体   繁体   English

js 模块在多页 web 应用程序中的使用(Closure 编译器)

[英]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.我有一个 web 应用程序,其中包含几个页面,其中包含一些共享代码的 js 文件。

- 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.共享文件与 page1 一起加载,单击按钮时,页面更改为 page2 或 page3。 I use Closure Compiler and every page is a chunk.我使用 Closure Compiler,每一页都是一个块。

--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.我重构了 js 文件以使用导入/导出。 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.例如:page2 和 page3 是空的。

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.但是,由于许多代码是共享的,因此文件 output 会更大,因为共享代码无法使用。 (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参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports

Note: Webpack handles dynamic chunks well enough.注意:Webpack 可以很好地处理动态块。 However I didn't tested this with Closure.但是我没有用 Closure 测试这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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