Node.js中如何实现CommonJS模块化?

2026-06-09 11:052阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计347个文字,预计阅读时间需要2分钟。

Node.js中如何实现CommonJS模块化?

下载并安装node.js | 创建项目结构 | 使用commonJS模块规范 | module1.js | module2.js | module3.js | app.js | package.json { name: commonJS-node, version: 1.0.0 } | 下载第三方模块npm install uniq --save | 对module1.js进行模块化编码

Node.js中如何实现CommonJS模块化?


  1. 下载安装node.js
  2. 创建项目结构

|-modules
|-module1.js
|-module2.js
|-module3.js
|-app.js
|-package.json
{
"name": "commonJS-node",
"version": "1.0.0"
}

  1. 下载第三方模块
  • npm install uniq --save
  1. 模块化编码
  • module1.js

module.exports = {
foo() {
console.log('moudle1 foo()')
}
}

  • module2.js

module.exports = function () {
console.log('module2()')
}

  • module3.js

exports.foo = function () {
console.log('module3 foo()')
}

exports.bar = function () {
console.log('module3 bar()')
}

  • app.js

/**
1. 定义暴露模块:
module.exports = value;
exports.xxx = value;
2. 引入模块:
var module = require(模块名或模块路径);
*/
"use strict";
//引用模块
let module1 = require('./modules/module1')
let module2 = require('./modules/module2')
let module3 = require('./modules/module3')

let uniq = require('uniq')
let fs = require('fs')

//使用模块
module1.foo()
module2()
module3.foo()
module3.bar()

console.log(uniq([1, 3, 1, 4, 3]))

fs.readFile('app.js', function (error, data) {
console.log(data.toString())
})

  1. 通过node运行app.js
  • 命令: node app.js
  • 工具: 右键–>运行


本文共计347个文字,预计阅读时间需要2分钟。

Node.js中如何实现CommonJS模块化?

下载并安装node.js | 创建项目结构 | 使用commonJS模块规范 | module1.js | module2.js | module3.js | app.js | package.json { name: commonJS-node, version: 1.0.0 } | 下载第三方模块npm install uniq --save | 对module1.js进行模块化编码

Node.js中如何实现CommonJS模块化?


  1. 下载安装node.js
  2. 创建项目结构

|-modules
|-module1.js
|-module2.js
|-module3.js
|-app.js
|-package.json
{
"name": "commonJS-node",
"version": "1.0.0"
}

  1. 下载第三方模块
  • npm install uniq --save
  1. 模块化编码
  • module1.js

module.exports = {
foo() {
console.log('moudle1 foo()')
}
}

  • module2.js

module.exports = function () {
console.log('module2()')
}

  • module3.js

exports.foo = function () {
console.log('module3 foo()')
}

exports.bar = function () {
console.log('module3 bar()')
}

  • app.js

/**
1. 定义暴露模块:
module.exports = value;
exports.xxx = value;
2. 引入模块:
var module = require(模块名或模块路径);
*/
"use strict";
//引用模块
let module1 = require('./modules/module1')
let module2 = require('./modules/module2')
let module3 = require('./modules/module3')

let uniq = require('uniq')
let fs = require('fs')

//使用模块
module1.foo()
module2()
module3.foo()
module3.bar()

console.log(uniq([1, 3, 1, 4, 3]))

fs.readFile('app.js', function (error, data) {
console.log(data.toString())
})

  1. 通过node运行app.js
  • 命令: node app.js
  • 工具: 右键–>运行