码迷,mamicode.com
首页 > Web开发 > 详细

Nodejs的模块化

时间:2019-09-02 15:39:37      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:https   ejs   方法   需要   参数   错误   sea   amd   save   

Node.js中的模块化

好处:

复用性高,一次定义,多次使用
前端模块化

AMD
AMD的实现需要使用 require.js
CMD
CMD的实现需要使用 sea.js 【 不更新 】
Common.js
Node.js使用了Common.js规范
内置模块引用
自定义模块引用
第三方模块引用
EcmaScript 模块化
es5
module.export / exports
es6
export default / export
export default 默认导出一个 , import xx from xxx
export 批量导出,导出多个, import { xxx } from xxx

Node.js中内置模块使用

  1. 格式: var/let/const 变量名 = require(路径) 内置模块路径就是模块名称
  2. 使用内置模块身上的方法
    const fs = require( ‘fs‘ )

    fs.readFile(‘../dist/1.txt‘,‘utf8‘,( error,docs ) => {
    console.log( docs )
    })

    request第三方模块

    作用: 数据请求
    使用:
    1. 安装

      npm/cnpm i/install request --dev-save/-D 开发环境安装
      npm/cnpm i/install request --save/-S 生产环境安装

    2. 导入
      let/var/const 变量名 = require( 模块名称 )
    3. 使用

在Node.js文件中进行数据请求,不存在跨域
const request = require( ‘request‘ )

request(‘https://m.lagou.com/listmore.json‘,( error,response,body ) => {
// 参数说明: error 错误信息 response 响应结果 body 获取的数据

console.log( body )

})

自定义模块

步骤:
1.创建模块 【 Function / Object / String 】
const name = {
firstName:‘show‘,
lastName: ‘lu‘
}
2.导出模块
- module.exports = 模块名称 导出一个
- module.exports = {} // 导出多个
const crad = {
sex: ‘nan‘,
age: ‘18‘

};
module.exports = name;

module.exports = {
name,crad
};
3.导入模块
const { name } = require( ‘./name.js‘ )

const { name,crad } = require( ‘./age.js‘ )

Nodejs的模块化

标签:https   ejs   方法   需要   参数   错误   sea   amd   save   

原文地址:https://www.cnblogs.com/zhaoqianguo/p/11446823.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!