【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
相关推荐
水冗水孚3 小时前
🚀四种方案解决浏览器地址栏预览txt文本乱码问题🚀Content-Type: text/plain;没有charset=utf-8
javascript·nginx·node.js
程序猿小D1 天前
第29节 Node.js Query Strings
node.js·vim·express
前端服务区1 天前
CommonJS 模块化的实现源码解析
node.js
前端服务区1 天前
发布npm包
node.js
sg_knight1 天前
Rollup vs Webpack 深度对比:前端构建工具终极指南
前端·javascript·webpack·node.js·vue·rollup·vite
啃火龙果的兔子1 天前
在服务器上使用 Docker 部署 Node.js 后端服务和前端项目
服务器·docker·node.js
Smile_Gently1 天前
Mac 系统 Node.js 安装与版本管理指南
macos·node.js
a别念m1 天前
webpack基础与进阶
前端·webpack·node.js
qq_12498707531 天前
基于Node.js的线上教学系统的设计与实现(源码+论文+调试+安装+售后)
java·spring boot·后端·node.js·毕业设计
程序猿小D1 天前
第28节 Node.js 文件系统
服务器·前端·javascript·vscode·node.js·编辑器·vim