问题
This loads jquery only once:
<script type="module">
import "./js/jquery.js";
import "./js/jquery.js";
</script>
The same is true for:
<script type="module">
import "./js/jquery.js";
</script>
<script type="module">
import "./js/jquery.js";
</script>
But this loads jquery two times:
<script src="./js/jquery.js"></script>
<script type="module">
import "./js/jquery.js";
</script>
Is it possible somehow to tell the browser's ES6 modules resolver that after first
<script src="./js/jquery.js"></script>
jquery scirpt is allready loaded and it is possible to use it without involving network/disk cache request?
P.S. This is just investigation. I'm thinking how we can mix modern ES6 modules and "legacy code" (in modern browsers) together. I would prefer to load jquery plugin system through "old style <script>
" since inline code depends on it.
I know that jquery is not good sample it doesn't have exports. Still we use it with babel import $ from jQuery;
and I want to understand what kind of transformations should be done during transpiling to prepare code be loaded with ES6 modules native support. If you know such babel 7 plugins - this is also very valuable.
回答1:
As a workaround, you could import the library in a module and "export" it to the old style scripts by adding it to the global scope. Just make sure the old style code only tries to access the library after the module has run.
<script type="module">
import jQuery from "./jquery-es6.js";
window.$ = jQuery;
</script>
If the library is not an es6 module, then you can do the opposite: include the script in the old style way, and then fetch it from the global scope in your new style code. Assyming jquery.js
does window.$ = jQuery
:
<script src="./js/jquery.js"></script>
<script type="module">
const jQuery = window.$;
</script>
This means you can't use your modules as-is in some other environment where window.$
is not set, but if you treat const jQuery = window.$
as a sort of "legacy import" and always do it at the top of the module and don't reference window.$
anywhere else, then upgrading to real imports later will be pretty easy.
来源:https://stackoverflow.com/questions/51921815/how-to-make-script-loading-and-es6-module-loading-working-together