加载某个目录到一个对象上

如果我想加载某个目录到一个对象上,需要如何做呢?

准备

  1. mkdir require-dictory
  2. cd require-dictory
  3. ls
  4. npm init
  5. npm i -S require-directory
  6. touch index.js

核心代码

  1. var requireDirectory = require('require-directory');
  2. module.exports = requireDirectory(module);

测试

touch test.js

  1. var obj = require('./index')
  2. console.log(obj);

然后

  1. require-dictory git:(master) node test.js
  2. { node_modules: { 'require-directory': { index: [Object], package: [Object] } },
  3. package:
  4. { name: 'require-dictory',
  5. version: '1.0.0',
  6. description: '',
  7. main: 'index.js',
  8. scripts: { test: 'echo "Error: no test specified" && exit 1' },
  9. author: '',
  10. license: 'ISC',
  11. dependencies: { 'require-directory': '^2.1.1' } },
  12. test: {} }

此时index对象就返回了index和test和package.json里的内容

测试,创建third.js

  1. require-dictory git:(master) touch third.js
  2. require-dictory git:(master) node test.js
  3. { node_modules: { 'require-directory': { index: [Object], package: [Object] } },
  4. package:
  5. { name: 'require-dictory',
  6. version: '1.0.0',
  7. description: '',
  8. main: 'index.js',
  9. scripts: { test: 'echo "Error: no test specified" && exit 1' },
  10. author: '',
  11. license: 'ISC',
  12. dependencies: { 'require-directory': '^2.1.1' } },
  13. test: {},
  14. third: {} }

此时,这个模块就写完啦,打印出当前模块下的挂载的所有对象

如何发布npm模块

那么我们来发布一个吧,顺便学习一下如何发布npm模块

  • 登陆npm
  • 发布
  1. require-dictory git:(master) nrm use npm
  2. Registry has been set to: https://registry.npmjs.org/
  3. require-dictory git:(master) npm login
  4. Username: i5ting
  5. Password:
  6. Email: (this IS public) shiren1118@126.com

一定要注意nrm use npm,源一定要是npmjs,不然是无法登陆成功的。

然后在package.json所在目录里

  1. npm publish .

即可

可以在package.json里增加start,每次发布模块的时候能简单点