Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why can't my HTML file find the JavaScript function from a sourced module?
When an HTML file cannot find JavaScript functions from a sourced module, it's usually because the function isn't properly exported from the module or the import statement is incorrect. ES6 modules require explicit export/import statements to share functions between files.
The Export Problem
Functions in JavaScript modules are not globally accessible unless explicitly exported. Without the export keyword, functions remain private to the module.
demo.js
console.log("function will import");
export function test(){
console.log("Imported!!!");
}
Example: Complete Module Import
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Module Import Example</title>
</head>
<body>
<h1>JavaScript Module Import</h1>
<script type="module">
import { test } from "./demo.js";
test();
</script>
</body>
</html>
function will import Imported!!!
Common Export Methods
JavaScript modules support different export patterns:
// Named export (recommended)
export function myFunction() { }
// Default export
export default function() { }
// Multiple named exports
export { func1, func2, variable };
Key Requirements
| Requirement | Description |
|---|---|
type="module" |
Required in script tag for ES6 modules |
export keyword |
Functions must be explicitly exported |
| File server | Modules require HTTP server (not file:// protocol) |
Troubleshooting Tips
If imports still fail, check these common issues:
- Ensure the script tag has
type="module" - Verify file paths are correct (case-sensitive)
- Run from a local server, not directly opening HTML files
- Check browser console for CORS or module loading errors
Conclusion
JavaScript modules require explicit export statements and type="module" in script tags. Always serve files through a local server for proper module loading.
