Node.js中Import与Require问题:csvtojson导入失败求助
import { csv } from 'csvtojson' Fails But const csv = require('csvtojson') Works in Node.js Hey there! Let's break down why your ES module import isn't cooperating with csvtojson while the CommonJS require works flawlessly. Here are the most likely issues and their fixes:
1. You're targeting the wrong export type
When you use const csv = require('csvtojson'), you're pulling in the module's default export. But import { csv } from 'csvtojson' tries to grab a named export called csv—which doesn't exist in this package. The two syntaxes don't map directly here.
Fix:
Use the default import instead, which matches what require does:
import csv from 'csvtojson';
This works because require() always returns the module's module.exports, which translates to the ES module's default export.
2. Node.js is treating your file as a CommonJS module
Node.js defaults to treating .js files as CommonJS modules. If you use import without explicitly enabling ES modules, Node will throw an error.
Fixes:
Option 1: Enable ES modules project-wide
Add"type": "module"to your project'spackage.jsonat the top level:{ "type": "module", // ... rest of your package.json content }This tells Node to interpret all
.jsfiles in your project as ES modules.Option 2: Use the
.mjsfile extension
If you don't want to change the whole project's module system, rename your file fromfilename.jstofilename.mjs. Node automatically recognizes.mjsfiles as ES modules.
3. Your Node.js version lacks proper ES module support
Older Node.js versions (pre-v14) had experimental or limited support for ES modules. If you're running v12 or earlier, even correct import syntax might fail.
Fix:
Upgrade to a LTS (Long-Term Support) version of Node.js (v14.x or newer). Check your current version with:
node -v
Quick Troubleshooting Checklist
- Replace
import { csv } from 'csvtojson'withimport csv from 'csvtojson' - Confirm your
package.jsonhas"type": "module"(or use.mjsfiles) - Ensure you're running Node.js v14 or later
After trying these steps, your import statement should work just like require did!
内容的提问来源于stack exchange,提问作者Shubham Singh

