This error message:
“An import declaration can only be used at the top level of a module.”
…means that you’re trying to use an import statement inside a function, conditional block, or any non-top-level scope, which is not allowed in JavaScript ES Modules.
Table of Contents
✅ Correct Usage (Top-Level):
// This is valid
import { readFile } from 'fs';
function readFileSync(path) {
readFile(path, (err, data) => {
if (err) throw err;
console.log(data.toString());
});
}
readFileSync('./file.txt');
❌ Incorrect Usage (Inside Function or Block):
// ❌ This will cause the error
function loadModule() {
import { readFile } from 'fs'; // ❌ Not allowed
readFile('./file.txt', (err, data) => {
if (err) throw err;
console.log(data.toString());
});
}
🚀 How to Fix It:
- Move
importto the top level:
import { readFile } from 'fs';
function loadFile() {
readFile('./file.txt', (err, data) => { if (err) throw err; console.log(data.toString()); });
}
loadFile();- For Dynamic Imports (if you need to import conditionally): Use the
import()function (dynamic import) instead ofimportsyntax:
async function loadModule()
{
const { readFile } = await import('fs'); // ✅ Dynamic import readFile('./file.txt', (err, data) => { if (err) throw err; console.log(data.toString()); });
}
loadModule();⚠️ Key Notes:
- Ensure your file is treated as an ES Module:
- In
package.json:"type": "module" - Or use
.mjsextension.
- In
- Dynamic imports (
import()) are supported in Node.js (v13.2.0+).
