https://github.com/rwu823/require-hooks
Node require hooks
https://github.com/rwu823/require-hooks
Last synced: 2 months ago
JSON representation
Node require hooks
- Host: GitHub
- URL: https://github.com/rwu823/require-hooks
- Owner: rwu823
- Created: 2016-05-08T14:31:42.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2023-12-15T05:23:46.000Z (over 1 year ago)
- Last Synced: 2025-04-11T16:14:23.584Z (3 months ago)
- Language: JavaScript
- Homepage: https://github.com/rwu823/require-hooks
- Size: 8.79 KB
- Stars: 7
- Watchers: 2
- Forks: 0
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
[](https://www.npmjs.org/package/rwu823/require-hooks) [](https://travis-ci.org/rwu823/require-hooks) [](https://coveralls.io/github/rwu823/require-hooks)
# 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
```javascript
// 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
```javascript
// 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
``````javascript
// test.spec.jsimport Tab from '../components/react-tab' // OOPS, throws exception :(
describe('#Test react tab component', ()=> {
...
})
```Includes require hooks to fix this
```javascript
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###