You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript技术问题:如何定义可导入的JS方法并调用导入文件中的方法

问题1:调用已导入JS文件中的方法

根据运行环境的不同,主要有两种常见的模块系统实现方式:

浏览器环境(ES6模块)

  1. 确保导入的目标JS文件为ES6模块格式,在当前文件中使用import语句导入目标方法:
    • 假设目标文件utils.js中导出了bar方法,当前文件代码示例:
      // 导入单个指定方法
      import { bar } from './utils.js';
      // 直接调用方法
      bar();
      
      // 或者导入整个模块,通过模块对象调用方法
      import * as utils from './utils.js';
      utils.bar();
      
    • 注意:浏览器中使用ES6模块时,需在HTML的<script>标签添加type="module"属性,示例:
      <script type="module" src="当前文件.js"></script>
      

Node.js环境(CommonJS/ES6模块)

CommonJS(Node.js默认模块系统)

若目标文件采用CommonJS格式导出,当前文件用require导入:

// 解构导入单个方法
const { bar } = require('./utils.js');
bar();

// 导入整个模块对象
const utils = require('./utils.js');
utils.bar();

ES6模块(Node.js需提前配置)

若Node.js项目启用ES6模块(如在package.json中设置"type": "module"),写法与浏览器环境一致:

import { bar } from './utils.js';
bar();

问题2:在test.js中定义方法'foo'并允许其他文件导入调用

同样分两种模块系统实现:

ES6模块格式

导出单个方法

// test.js
// 直接定义并导出
export function foo() {
  console.log('执行foo方法');
}

// 或先定义再导出
function foo() {
  console.log('执行foo方法');
}
export { foo };

默认导出(适合foo为模块核心方法的场景)

// test.js
export default function foo() {
  console.log('执行foo方法');
}

其他文件导入默认导出的写法:

import foo from './test.js';
foo();

CommonJS格式(Node.js环境)

导出单个方法

// test.js
function foo() {
  console.log('执行foo方法');
}
module.exports = { foo };

直接挂载到导出对象

// test.js
module.exports.foo = function() {
  console.log('执行foo方法');
};

其他文件的导入调用方式与问题1中的CommonJS示例一致。

内容的提问来源于stack exchange,提问作者Black

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 15:50:15