added ref-counted api

fixes #4
master
Tobias Koppers 2014-01-27 11:41:56 +01:00
parent 50729899f8
commit a407e48e00
2 changed files with 54 additions and 1 deletions

View File

@ -2,12 +2,14 @@
## Usage
### Simple API
``` javascript
require("style!raw!./file.css");
// => add rules in file.css to document
```
It's recommended to combine it with the [`css`](https://github.com/webpack/css-loader) loader: `require("style!css!./file.css")`.
It's recommended to combine it with the [`css-loader`](https://github.com/webpack/css-loader): `require("style!css!./file.css")`.
It also possible to add a URL instead of a css string:
@ -16,6 +18,18 @@ require("style/url!file!./file.css");
// => add a <link rel="stlyesheet"> to file.css to document
```
### Reference-counted API
``` javascript
var style = require("style/useable!css!./file.css");
style.use(); // = style.ref();
style.unuse(); // = style.unref();
```
Styles are not added on require, but instead on call to `use`/`ref`. Styles are removed from page if `unuse`/`unref` is called exactly as often as `use`/`ref`.
Note: Behavior is undefined when `unuse`/`unref` is called more often than `use`/`ref`. Don't do that.
## License
MIT (http://www.opensource.org/licenses/mit-license.php)

39
useable.js Normal file
View File

@ -0,0 +1,39 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var path = require("path");
module.exports = function() {};
module.exports.pitch = function(remainingRequest) {
this.cacheable && this.cacheable();
return [
"var refs = 0;",
"var dispose;",
"exports.use = exports.ref = function() {",
" if(!(refs++)) {",
" dispose = require(" + JSON.stringify("!" + path.join(__dirname, "addStyle.js")) + ")(require(" + JSON.stringify("!!" + remainingRequest) + "));",
" }",
" return exports",
"};",
"exports.unuse = exports.unref = function() {",
" if(!(--refs)) {",
" dispose();",
" dispose = null;",
" }",
"};",
"if(module.hot) {",
" refs = module.hot.data && module.hot.data.refs || 0;",
" if(refs) {",
" refs--;",
" exports.ref();",
" }",
" module.hot.accept();",
" module.hot.dispose(function(data) {",
" data.refs = refs;",
" if(dispose) {",
" dispose();",
" }",
" });",
"}",
].join("\n");
};