To use <script type="module"> and access variables between different <script> tags, you need to understand how ES Modules (ESM) work in JavaScript. Here's a structured explanation:
1. What is <script type="module">?
- When you use
type="module", the script is treated as an ES Module, which has:
- Strict scope: Variables declared in the module are not automatically added to the global scope (e.g.,
window).
- Export/Import system: You must explicitly export values and import them in other modules.
2. How to Export Variables from a Module
To share variables between modules, you must export them.
Example:
<!-- script1.html -->
<script type="module">
// Export a variable
export let myVar = 42;
</script>
3. How to Import Variables in Another Module
In another module, use import to access the exported variables.
Example:
<!-- script2.html -->
<script type="module">
// Import the variable
import { myVar } from './script1.js';
console.log(myVar); // Output: 42
</script>
Note: The import path must point to a valid module file (e.g., ./script1.js). Inline scripts (like <script type="module">...</script>) cannot be directly imported unless you use a bundler (e.g., Webpack, Vite).
4. Accessing Variables in Non-Module Scripts
If the second script is not a module (i.e., no type="module"), it cannot directly access variables from a module. However, you can work around this by attaching variables to the global window object.
Example:
<!-- script1.html -->
<script type="module">
// Export to global scope
window.myVar = 42;
</script>
<!-- script2.html -->
<script>
// Access the global variable
console.log(window.myVar); // Output: 42
</script>
Caution: This approach pollutes the global namespace and is not recommended for large projects. Use it sparingly.
5. Key Considerations
- Module Scope: Variables in modules are not globally accessible unless explicitly exported or attached to
window.
- Execution Order: Modules are loaded asynchronously. Ensure the module is fully loaded before accessing its variables (e.g., using
await or DOMContentLoaded).
- File vs. Inline: Inline module scripts (e.g.,
<script type="module">...</script>) cannot be imported directly. Use external files or bundlers for cross-module access.
6. Example with External Files
If you're using external files, the structure would look like this:
module1.js
export let myVar = 42;
module2.js
import { myVar } from './module1.js';
console.log(myVar); // Output: 42
index.html
<script type="module" src="module1.js"></script>
<script type="module" src="module2.js"></script>
7. Summary
| Scenario | Solution |
|---|
| Module to Module | Use export and import |
| Module to Non-Module | Attach to window (not recommended) |
| Inline Module to Inline Module | Use external files or bundlers |
By following these practices, you can effectively share variables between scripts while leveraging the benefits of ES Modules.