首页 > 解决方案 > js文件中的导入导出方法不起作用

问题描述

我想在我的 js 文件中导入一个函数。这是一个简单的代码:

// In index.js file
function addition(a, b) {
    return a + b;
}

export { addition };

// In test.js file

import { addition } from "./index.js";

console.log(addition(5, 4));

控制台中的结果: 在此处输入图像描述

谢谢 !

标签: javascriptvisual-studio-code

解决方案


NodeJS 使用不支持的 CommonJS 模块语法import/export,但需要module.exports像这样使用:

// In index.js file
function addition(a, b) {
    return a + b;
}

module.exports = addition;

// In test.js file

const addition = require("./index.js");

console.log(addition(5, 4));


推荐阅读