nodejs-hook 开发

nodejs require hook 功能很强大,我们可以用来将不支持的数据文件,直接使用require 进行加载,同时
我们可以方便的进行代码的预编译(比如babel 的组件)
为了方便使用npm 包,使用lerna 进行单体组件仓库的开发模式,demo 主要是加载markdown 文档

环境准备

  • 项目初始化
 
lerna init
mkdir -p packages/hook  packages/useage
 
  • 项目结构
├── README.md
├── lerna.json
├── package.json
└── packages
    ├── hook
    ├── compiler.js
    ├── hooks.js
    ├── index.js
    └── package.json
    └── useage
        ├── app.js
        ├── package.json
        └── users.md
 

代码说明

主要是hook,useage 是使用

  • hook
    hooks.js:
 
const addHook = function (ext, compile) {
    require.extensions[ext] = function hook(module, file) {
      const content = compile(file);
      return module._compile('module.exports = ' + JSON.stringify(content), file);
    }
  }
module.exports = addHook;
 
 

compiler.js:

const fs = require('fs');
const compiler = file => {
  const content = fs.readFileSync(file, { encoding: 'utf8' });
  return content;
}
module.exports = compiler;
 
 

index.js:

const hook = require('./hooks');
const compiler = require('./compiler');
module.exports = function ({ extensions }) {
  extensions = (extensions || []).map((ext) => ext.replace('.', ''));
  extensions.forEach((ext) => hook(`.${ext}`, compiler));
}
 
 
  • 使用
    添加package 引用
 
+ "dependencies": {
+ "hook":"1.0.0"
+ }
 
 

app.js:

require('hook')({
    extensions: ['txt', 'md'],
  });
const content = require("./users.md")
console.log(content)
 
 

运行&&测试

  • 初始化lerna 模块
lerna bootstrap
 
  • 运行
yarn s
 
  • 效果
yarn s
yarn run v1.10.1
warning package.json: No license field
$ lerna run --parallel s
lerna info version 2.11.0
lerna info run in 1 package(s): npm run s
useage: > useage@1.0.0 s /Users/dalong/mylearning/markdown-require-project/packages/useage
useage: > node app
useage: # userlists
useage: * dalong
useage: * demo
lerna success run Ran npm script 's' in packages:
lerna success - useage
Done in 1.23s.
 

Require Extensions 原理

https://gist.github.com/jamestalmage/df922691475cff66c7e6 这篇文档不错,很清晰

参考资料

https://gist.github.com/jamestalmage/df922691475cff66c7e6
https://github.com/rongfengliang/require-hook-learning

posted on   荣锋亮  阅读(1703)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2016-12-20 rabiitmq集群完整安装
2014-12-20 Mysql 批量插入数据的方法
2013-12-20 silverlight 进行本地串口调用的一种可行的解决方法 之silverlight端代码

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示