使用createRequire引入fs模块时遇Uncaught SyntaxError错误求助
createRequire Let’s break down why you’re hitting this error and fix it step by step:
Why the Error Pops Up
By default, Node.js treats .js files as CommonJS modules—and CommonJS doesn’t support the import statement. When you try to run import { createRequire } from 'module', Node.js throws an error because it doesn’t recognize your file as an ES module (the type that supports import syntax).
Solution 1: Mark Your Project as ES Modules via package.json
This is the cleanest approach if you want to use ES module syntax across your project:
- Open your project’s
package.jsonfile (create one withnpm init -yif you don’t have it). - Add a
"type": "module"field at the top level:{ "type": "module", // Keep your existing fields like "name", "scripts", etc. } - Now all
.jsfiles in your project will be treated as ES modules, and yourcreateRequirecode will work as intended:import { createRequire } from 'module'; const require = createRequire(import.meta.url); const fs = require('fs'); // Use fs methods like fs.readFile() or fs.writeFileSync() as usual
Solution 2: Rename Your File to .mjs
If you don’t want to adjust your entire project’s module system, simply rename your file from filename.js to filename.mjs. Node.js automatically treats .mjs files as ES modules, so the import statement will work without modifying package.json.
Solution 3: Use ES Module Syntax for fs Directly
Since you’re trying to import fs, you could skip createRequire entirely and use native ES module syntax (supported in Node.js 14.13.0+):
import * as fs from 'fs'; // Or use default imports (works in newer Node.js versions): // import fs from 'fs'; // Use fs methods just like you would with require
Quick Check: Node.js Version
Make sure you’re running Node.js 14.13.0 or later. Older versions required the --experimental-modules flag to use ES modules, but that’s no longer needed in modern releases.
内容的提问来源于stack exchange,提问作者AVB

