Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add ID's to <style> tags #336

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ Styles are not added on `import/require()`, but instead on call to `use`/`ref`.
|:--:|:--:|:-----:|:----------|
|**`hmr`**|`{Boolean}`|`true`|Enable/disable Hot Module Replacement (HMR), if disabled no HMR Code will be added (good for non local development/production)|
|**`base`** |`{Number}`|`true`|Set module ID base (DLLPlugin)|
|**`attrs`**|`{Object}`|`{}`|Add custom attrs to `<style></style>`|
|**`attrs`**|`{Object}`|`{}`|Add custom attrs to `<style></style>`, `[name]` `[version]` Can be replaced automatically|
|**`transform`** |`{Function}`|`false`|Transform/Conditionally load CSS by passing a transform/condition function|
|**`insertAt`**|`{String\|Object}`|`bottom`|Inserts `<style></style>` at the given position|
|**`insertInto`**|`{String\|Function}`|`<head>`|Inserts `<style></style>` into the given position|
Expand Down Expand Up @@ -199,6 +199,7 @@ This setting is primarily used as a workaround for [css clashes](https://github.
### `attrs`

If defined, style-loader will attach given attributes with their values on `<style>` / `<link>` element.
And you can distinguish source of styles.

**component.js**
```js
Expand All @@ -207,13 +208,22 @@ import style from './file.css'

**webpack.config.js**
```js
// static
{
test: /\.css$/,
use: [
{ loader: 'style-loader', options: { attrs: { id: 'id' } } }
{ loader: 'css-loader' }
]
}
// replaceable
{
test: /\.css$/,
use: [
{ loader: 'style-loader', options: { attrs: { component: '[name]@[version]' } }
{ loader: 'css-loader' }
]
}
```

```html
Expand Down
12 changes: 11 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
Author Tobias Koppers @sokra
*/
var path = require("path");

var fs = require("fs");
var loaderUtils = require("loader-utils");
var validateOptions = require('schema-utils');
var findPackage = require('./lib/utils').findPackage;

module.exports = function () {};

Expand All @@ -14,6 +15,15 @@ module.exports.pitch = function (request) {

var options = loaderUtils.getOptions(this) || {};

var pkg = findPackage(fs, path.dirname(this.resourcePath)) || {};
if (options.attrs) {
Object.keys(options.attrs).forEach(function(key) {
options.attrs[key] = options.attrs[key]
.replace(/\[name\]/ig, pkg.name)
.replace(/\[version\]/ig, pkg.version);
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need use loader-utils.interpolateName (https://github.com/webpack/loader-utils#interpolatename).
Also find-package doesn't works good with mono repos, please don't use this package.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. find-package has been removed.
  2. But loader-utils.interpolateName is unsatisfactory. We need to get the version number of the package corresponding to the current file.
  3. is there a better way to get it than from package.json?

}

validateOptions(require('./options.json'), options, 'Style Loader')

options.hmr = typeof options.hmr === 'undefined' ? true : options.hmr;
Expand Down
6 changes: 1 addition & 5 deletions lib/addStyleUrl.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,7 @@
Author Tobias Koppers @sokra
*/

function addAttrs (element, attrs) {
Object.keys(attrs).forEach(function (key) {
element.setAttribute(key, attrs[key]);
});
}
var addAttrs = require('./utils').addAttrs;

module.exports = function addStyleUrl (url, options) {
if (typeof DEBUG !== "undefined" && DEBUG) {
Expand Down
40 changes: 40 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
var path = require("path");

var utils = {
exists: function (fileSystem, filename) {
var exists = false;
try {
exists = fileSystem.statSync(filename).isFile();
} catch (err) {
if (err.code !== "ENOENT") throw err;
}

return exists;
},

findPackage: function (fileSystem, start) {
var file = path.join(start, "package.json");
if (utils.exists(fileSystem, file)) {
return require(file);
}

var up = path.dirname(start);

// Reached root
if (up !== start) {
return utils.findPackage(fileSystem, up);
}
return null;
},

addAttrs: function (element, attrs) {
Object.keys(attrs).forEach(function (key) {
element.setAttribute(key, attrs[key]);
});
},
};

module.exports = utils;



10 changes: 7 additions & 3 deletions test/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,10 @@ describe("basic tests", function() {

it("attrs", function(done) {
// Setup
styleLoaderOptions.attrs = {id: 'style-tag-id'};
styleLoaderOptions.attrs = {
id: 'style-tag-id',
component: '[name]@[version]',
};

fs.writeFileSync(
rootDir + "main.js",
Expand All @@ -235,12 +238,13 @@ describe("basic tests", function() {
].join("\n")
);

const { version, name } = require('../package.json');

// Run
let expected = [
existingStyle,
`<style id="${styleLoaderOptions.attrs.id}" type="text/css">${requiredCss}</style>`
`<style id="${styleLoaderOptions.attrs.id}" component="${name}@${version}" type="text/css">${requiredCss}</style>`
].join("\n");

runCompilerTest(expected, done);
}); // it attrs

Expand Down
51 changes: 51 additions & 0 deletions test/utils.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
var assert = require("assert");
var fs = require("fs");
var path = require("path");
var jsdom = require('jsdom');
var utils = require("../lib/utils");

var exists = utils.exists;
var findPackage = utils.findPackage;
var addAttrs = utils.addAttrs;

describe('Utils Test', () => {
it("exist", function(done) {
assert.equal(exists(fs, path.join(__dirname, 'basic.test.js')), true);
done();
});

it('not exist', function(done) {
assert.equal(exists(fs, path.join(__dirname, 'xx.js')), false);
done();
});

it('findPackage', function(done) {
assert.equal(findPackage(fs, __dirname).name, 'style-loader');
done();
});

it('findPackage null', function(done) {
assert.equal(findPackage(fs, '/'), null);
done();
});

it('addAttrs', function(done) {
jsdom.env(
'<p></p>',
[],
function (err, window) {
var doc = window.document;
var ele = doc.createElement('div');
var attrs = {
id: 'div',
width: '100px'
};
addAttrs(ele, attrs);
assert.equal(ele.id, 'div');
assert.equal(ele.getAttribute('width'), '100px');
window.close();
done();
}
);
});
});