Node.js导出hello_2018函数报错TypeError: xxx is not a function求助
Hey there! Let's figure out why you're hitting that TypeError: xxx is not a function when trying to use the hello_2018 function from your hello.js file. This is a super common pitfall in Node.js, so let's break down the most likely fixes step by step:
1. Double-check your export syntax in hello.js
The first thing to verify is how you're exporting the hello_2018 function. Node.js supports two main module systems—CommonJS (the default) and ES modules—and mixing up their syntax will cause errors.
CommonJS (default, no extra config needed)
Make sure you're attaching the function to module.exports or exports:
// hello.js function hello_2018() { return "Hello from 2018!"; } // Option 1: Explicit module.exports module.exports.hello_2018 = hello_2018; // Option 2: Shorthand exports (works the same for named exports) exports.hello_2018 = hello_2018;
ES Modules (requires config)
If you're using ES6 export syntax, you need to add "type": "module" to your package.json first. Then export the function like this:
// hello.js export function hello_2018() { return "Hello from 2018!"; }
2. Match your import syntax to the export
Your import method has to line up exactly with how you exported the function. Mismatching these is the #1 cause of this error.
For CommonJS named exports
Use object destructuring or access the function directly from the imported module:
// Calling file // Option 1: Destructure the function const { hello_2018 } = require('./hello.js'); hello_2018(); // Should work now // Option 2: Access via the module object const helloModule = require('./hello.js'); helloModule.hello_2018();
For ES Modules named exports
Import with destructuring (and remember the package.json config):
// Calling file import { hello_2018 } from './hello.js'; hello_2018();
Watch out for default export mistakes
If you accidentally used a default export (like module.exports = hello_2018), trying to destructure it will fail. For example:
// Wrong: Trying to destructure a default export const { hello_2018 } = require('./hello.js'); // This throws the TypeError // Correct: Import the default export directly const hello_2018 = require('./hello.js');
3. Verify your file path
Make sure the path in require() or import points to the correct hello.js file. If it's in the same directory, you must use ./hello.js (not just hello.js—that would look for a package in node_modules). A wrong path might import an empty object or unrelated module, leading to the function not being found.
4. Debug with a quick console log
If you're still stuck, add a log to see what you're actually importing:
const helloModule = require('./hello.js'); console.log(helloModule);
- If it logs
{}, your export is broken. - If it logs the function itself, you used a default export but tried a named import.
- If it logs an object with other properties, check if you misspelled
hello_2018.
内容的提问来源于stack exchange,提问作者user824624

