【Node.js】module 模块化

认识 node.js

Node.js 是一个独立的 JavaScript 运行环境,能独立执行 JS 代码,可以用来编写服务器后端的应用程序。基于Chrome V8 引擎封装,但是没有 DOM 和 BOM。Node.js 没有图形化界面。node -v 检查是否安装成功。node index.js 执行该文件夹下的 index.js 文件。

modules 模块化

commonJS 写法

js 复制代码
// a.js
const Upper = (str) => {
  return str.substring(0,1).toUpperCase() + str.substring(1)
}
const fn = () => {
  console.log("this is a")
}
// 接口暴露方法一:
// module.exports = {
//   upper: Upper,
//   fn
// }
// 接口暴露方法二:
exports.upper = Upper
exports.fn = fn
js 复制代码
// index.js
const A = require('./modules/a')
A.fn()  // this is a
console.log(A.upper('hello'))  // Hello

ES 写法

需要先 npm install 安装依赖,生成 node_modules 文件夹,然后在 package.json 中配置 "type": "module",,之后才可以使用这种写法。

js 复制代码
// a.js
const Upper = (str) => {
  return str.substring(0,1).toUpperCase() + str.substring(1)
}
const fn = () => {
  console.log("this is a")
}
// 接口暴露方法一:
// module.exports = {
//   Upper,
//   fn
// }
// 接口暴露方法二:
// exports.upper = Upper
// exports.fn = fn
// 接口暴露方法三:
export {
  Upper,
  fn
}
js 复制代码
// index.js
// const fnn = require('./modules/a')
// 注意:此时导入a.js 文件必须加上 js 后缀
import { Upper } from './modules/a.js'
console.log(Upper('hello'))  // Hello
相关推荐
一心赚狗粮的宇叔2 小时前
VScode常用扩展包&Node.js安装及npm包安装
vscode·npm·node.js·web
花间相见2 小时前
【AI开发】—— Ubuntu系统使用nvm管理Node.js多版本,版本切换一键搞定(实操完整版)
linux·ubuntu·node.js
嘿是我呀3 小时前
【用npm安装node时报错“npm 无法加载文件”】
前端·npm·node.js
西门吹-禅1 天前
prisma
node.js
怪兽毕设1 天前
基于SpringBoot的选课调查系统
java·vue.js·spring boot·后端·node.js·选课调查系统
心.c1 天前
Vue3+Node.js实现文件上传分片上传和断点续传【详细教程】
前端·javascript·vue.js·算法·node.js·哈希算法
roamingcode1 天前
我是如何 Vibe Coding,将 AI CLI 工具从 Node.js 迁移到 Rust 并成功发布的
人工智能·rust·node.js·github·claude·github copilot
Stream_Silver3 天前
【Node.js 安装报错解决方案:解决“A later version of Node.js is already installed”问题】
node.js
Anthony_2313 天前
基于 Vue3 + Node.js 的实时可视化监控系统实现
node.js
说给风听.3 天前
解决 Node.js 版本冲突:Windows 系统 nvm 安装与使用全指南
windows·node.js