JavaScript模块导出问题求助:新手开发者遇导出失效困惑
Hey there! Let's break down why your module export might not be working. First off, the code you wrote for exporting the add function using CommonJS syntax is actually valid—so the problem is almost certainly with how you're importing it, or the environment you're running your code in.
Let's go through the most common fixes:
Double-check your import syntax
If you're using Node.js (which uses CommonJS by default), you need to import the module withrequire()like this:// 两种正确的导入方式 // 方式1:解构出add函数 const { add } = require('./your-module-filename.js'); // 方式2:先导入整个模块,再调用方法 const mathModule = require('./your-module-filename.js'); mathModule.add(2, 3); // 应该返回5If you tried using ES Module syntax (like
import { add } from './your-module.js') without configuring your project to support ES Modules (like adding"type": "module"to yourpackage.json), that would cause an error.Verify your file path and name
It sounds simple, but typos or incorrect relative paths are super common. Make sure the path inrequire()matches exactly where your module file is located. For example, if your module is in the same folder as the file importing it, you need the./prefix (like./math.jsinstead of justmath.js).Check if your environment supports CommonJS
Browsers don't natively supportmodule.exports—if you're trying to run this code directly in the browser, you'll need to either:- Use a bundler like Webpack or Vite to package your modules, or
- Switch to ES Module syntax instead:
// 改用ES模块导出 export const add = function(a, b) { return a + b }; // 然后在HTML的script标签里加上type="module" // <script type="module" src="your-script.js"></script>
Just to confirm, your original export code is totally valid for CommonJS environments:
var add = function(a, b) { return a+b } module.exports = { add: add }
You could even simplify it to make it a bit cleaner:
module.exports = { add: (a, b) => a + b }
Start by checking how you're importing the module—9 times out of 10, that's where the issue is!
内容的提问来源于stack exchange,提问作者Keith007

