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