2 scripts are connected to the page:
<script src="script.js"></script> <script src="DOMOperations.js" type="module"></script> DOMOperations is a module that provides some wrappers for DOM operations:
// DOMOperations.js export function printToBody(str) { let textNode = document.createTextNode(str); document.body.appendChild(textNode); } script is the main script that imports some functionality provided by the module:
// script.js import {printToBody} from "./DOMOperations.js"; printToBody("Hello!"); But with this connection of scripts, nothing works, because, as FireFox says, import expressions can only be at the top level of the module :
SyntaxError: import declarations
OK, we point out that the main script is a module:
<script src="script.js" type="module"></script> <script src="DOMOperations.js"></script> But now, even though everything seems to be working, there is still an error in the console, the truth is different:
SyntaxError: export declarations
That is, export expressions can only be at the top level of a module. It turns out, it is necessary to connect both files as modules?
<script src="script.js" type="module"></script> <script src="DOMOperations.js" type="module"></script> So it also works, and there are no errors. But a completely logical question arises: where is the logic?
Why import expressions can appear only in the module ? After all, it is much more likely that I want to import some functionality provided by the module, that is, from the module, and not vice versa.
I would think that this is due to the fact that the implementation of the modules is still at an early stage (moreover, it is available only with certain browser settings), but even those few examples that I managed to find on the Internet also use this approach:
<script type="module"> import {addTextToBody} from './utils.js'; // импорты в модуле! addTextToBody('Modules are pretty cool.'); </script> Please explain why this is implemented in this way.