require-hooks

0.0.6 • Public • Published

version Build Status Coverage

Node Require Hooks

In browser's world we have webpack and many great loaders let us require everything not only .js file, on the contrary you only can require .js in Node.

Usage

// include in main file
import requireHooks from 'require-hooks'
import fs, {readFileSync} from 'fs'
  
requireHooks(({ext, rawPath, mod, requirePath})=> {
  switch (ext) {
    case '.css': // require('./[everything].css') will as 'css'
      return 'css'
    case '.raw': // return file raw body
      return readFileSync(rawPath).toString()
    case '.md': // do nothing
      return null
  }
})

Examples

Without require hooks

// react-tab.js
import React, {Component} from 'react'
 
// this will get exception in Node test environment
require('./react-tab.css') 
 
class Tab extends Component {
  ...
}
 
module.export = Tab
// test.spec.js
 
import Tab from '../components/react-tab' // OOPS, throws exception :(
  
describe('#Test react tab component', ()=> {
    ...
})

Includes require hooks to fix this

require('require-hooks')(({ext, mod, requirePath})=> {
  switch (ext) {
    case '.css': // do nothing
      return null
  }
})
 
import Tab from '../components/react-tab' // Congratulation, pass the require :)    
               
describe('#Test react tab component', ()=> {
    ...
})

API

requireHooks({ext, raw, mod, requirePath})

If doesn't have any return it will uses original require function

  • ext get filename extension
  • mod export as module
  • requirePath get relative require path
  • rawPath get full raw path

Readme

Keywords

Package Sidebar

Install

npm i require-hooks

Weekly Downloads

5

Version

0.0.6

License

MIT

Last publish

Collaborators

  • rwu823