Skip to content
This repository has been archived by the owner on Oct 9, 2020. It is now read-only.

feat: support returning SVG as a {String} (options.raw) #62

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Copyright JS Foundation and other contributors

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
114 changes: 95 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,39 @@
**NOTICE [2016-06-26]: I'm not using or developing this lib anymore. Therefore I'm closing issues (which I cannot handle anymore), but you can send PR to improve or fix problems you facing with this lib.**

# SVG Inline Loader for Webpack

This Webpack loader inlines SVG as module. If you use Adobe suite or Sketch to export SVGs, you will get auto-generated, unneeded crusts. This loader removes it for you, too.
[![npm][npm]][npm-url]
[![deps][deps]][deps-url]
[![test][test]][test-url]
[![coverage][cover]][cover-url]
[![chat][chat]][chat-url]

<div align="center">
<!-- replace with accurate logo e.g from https://worldvectorlogo.com/ -->
<a href="https://github.com/webpack/webpack">
<img width="200" height="200" vspace="" hspace="25"
src="https://cdn.rawgit.com/webpack/media/e7485eb2/logo/icon.svg">
</a>
<h1>SVG Inline Loader for Webpack</h1>
<p>This Webpack loader inlines SVG as module. If you use Adobe suite or Sketch to export SVGs, you will get auto-generated, unneeded crusts. This loader removes it for you, too.<p>
</div>

<h2 align="center">Install</h2>

```bash
npm install svg-inline-loader --save-dev
```

## Config
<h2 align="center">Configuration</h2>

Simply add configuration object to `module.loaders` like this.

```javascript
{
test: /\.svg$/,
loader: 'svg-inline'
loader: 'svg-inline-loader'
}
```

warning: You should configure this loader only once via `module.loaders` or `require('!...')`. See [#15](https://github.com/sairion/svg-inline-loader/issues/15) for detail.
warning: You should configure this loader only once via `module.loaders` or `require('!...')`. See [#15](https://github.com/webpack-contrib/svg-inline-loader/issues/15) for detail.

### query options
<h2 align="center">Query Options</h2>

#### `removeTags: boolean`

Expand All @@ -31,6 +47,12 @@ warning: this won't work unless you specify `removeTags: true`

default: `removingTags: ['title', 'desc', 'defs', 'style']`

#### `warnTags: [...string]`

warns about tags, ex: ['desc', 'defs', 'style']

default: `warnTags: []`

#### `removeSVGTagAttrs: boolean`

Removes `width` and `height` attributes from `<svg />`.
Expand All @@ -43,6 +65,11 @@ Removes attributes from inside the `<svg />`.

default: `removingTagAttrs: []`

#### `warnTagAttrs: [...string]`

Warns to console about attributes from inside the `<svg />`.

default: `warnTagAttrs: []`
#### `classPrefix: boolean || string`

Adds a prefix to class names to avoid collision across svg files.
Expand All @@ -55,30 +82,79 @@ Adds a prefix to ids to avoid collision across svg files.

default: `idPrefix: false`

#### `raw: boolean`

Returns the content of the cleaned up SVG as a string instead of a module. Useful if you plan on passing
the output on to file-loader, etc.

default: `raw: false`

<h2 align="center">Example Usage</h2>

##### Example Usage
```js
// Using default hashed prefix (__[hash:base64:7]__)
var logoTwo = require('svg-inline?classPrefix!./logo_two.svg');
var logoTwo = require('svg-inline-loader?classPrefix!./logo_two.svg');

// Using custom string
var logoOne = require('svg-inline?classPrefix=my-prefix-!./logo_one.svg');
var logoOne = require('svg-inline-loader?classPrefix=my-prefix-!./logo_one.svg');

// Using custom string and hash
var logoThree = require('svg-inline?classPrefix=__prefix-[sha512:hash:hex:5]__!./logo_three.svg');
var logoThree = require('svg-inline-loader?classPrefix=__prefix-[sha512:hash:hex:5]__!./logo_three.svg');
```
See [loader-utils](https://github.com/webpack/loader-utils#interpolatename) for hash options.

Preferred usage is via a `module.loaders`:
```js
{
test: /\.svg$/,
loader: 'svg-inline?classPrefix'
loader: 'svg-inline-loader?classPrefix'
}
```

## Notes

- `<IconSVG />` React Component is **DEPRECATED**, use `svg-inline-react` package instead.
- Known problems:
- currently inlining SVG in css is unable. See #22
<h2 align="center">Maintainers</h2>

<table>
<tbody>
<tr>
<td align="center">
<img width="150" height="150"
src="https://avatars3.githubusercontent.com/u/166921?v=3&s=150">
</br>
<a href="https://github.com/bebraw">Juho Vepsäläinen</a>
</td>
<td align="center">
<img width="150" height="150"
src="https://avatars2.githubusercontent.com/u/8420490?v=3&s=150">
</br>
<a href="https://github.com/d3viant0ne">Joshua Wiens</a>
</td>
<td align="center">
<img width="150" height="150"
src="https://avatars3.githubusercontent.com/u/533616?v=3&s=150">
</br>
<a href="https://github.com/SpaceK33z">Kees Kluskens</a>
</td>
<td align="center">
<img width="150" height="150"
src="https://avatars3.githubusercontent.com/u/3408176?v=3&s=150">
</br>
<a href="https://github.com/TheLarkInn">Sean Larkin</a>
</td>
</tr>
<tbody>
</table>

[npm]: https://img.shields.io/npm/v/svg-inline-loader.svg
[npm-url]: https://npmjs.com/package/svg-inline-loader

[deps]: https://david-dm.org/webpack-contrib/svg-inline-loader.svg
[deps-url]: https://david-dm.org/webpack-contrib/svg-inline-loader

[chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg
[chat-url]: https://gitter.im/webpack/webpack

[test]: https://travis-ci.org/webpack-contrib/svg-inline-loader.svg?branch=master
[test-url]: https://travis-ci.org/webpack-contrib/svg-inline-loader

[cover]: https://codecov.io/gh/webpack-contrib/svg-inline-loader/branch/master/graph/badge.svg
[cover-url]: https://codecov.io/gh/webpack-contrib/svg-inline-loader
3 changes: 3 additions & 0 deletions config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ module.exports = {
],
removingTagAttrs: [],
classPrefix: false,
idPrefix: false,
warnTags: [],
warnTagAttrs: []
};
32 changes: 22 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ var simpleHTMLTokenizer = require('simple-html-tokenizer');
var tokenize = simpleHTMLTokenizer.tokenize;
var generate = simpleHTMLTokenizer.generate;
var loaderUtils = require('loader-utils');
var assign = require('object-assign');

var conditions = require('./lib/conditions');
var transformer = require('./lib/transformer');
Expand All @@ -16,19 +17,24 @@ var regexSequences = [
// SVG XML -> HTML5
[/\<([A-Za-z]+)([^\>]*)\/\>/g, "<$1$2></$1>"], // convert self-closing XML SVG nodes to explicitly closed HTML5 SVG nodes
[/\s+/g, " "], // replace whitespace sequences with a single space
[/\> \</g, "><"], // remove whitespace between tags
[/\> \</g, "><"] // remove whitespace between tags
];

function getExtractedSVG(svgStr, query) {
var config;
// interpolate hashes in classPrefix
if(!!query && !!query.classPrefix) {
const name = query.classPrefix === true ? '__[hash:base64:7]__' : query.classPrefix;
query.classPrefix = loaderUtils.interpolateName({}, name, {content: svgStr});
}
if(!!query) {
config = assign({}, query);

if (!!config.classPrefix) {
const name = config.classPrefix === true ? '__[hash:base64:7]__' : config.classPrefix;
config.classPrefix = loaderUtils.interpolateName({}, name, { content: svgStr });
}

if (!!query && !!query.idPrefix) {
const id_name = query.idPrefix === true ? '__[hash:base64:7]__' : query.idPrefix;
query.idPrefix = loaderUtils.interpolateName({}, id_name, {content: svgStr});
if (!!config.idPrefix) {
const id_name = config.idPrefix === true ? '__[hash:base64:7]__' : config.idPrefix;
config.idPrefix = loaderUtils.interpolateName({}, id_name, { content: svgStr });
}
}

// Clean-up XML crusts like comments and doctype, etc.
Expand All @@ -47,7 +53,7 @@ function getExtractedSVG(svgStr, query) {
}

// If the token is <svg> start-tag, then remove width and height attributes.
return generate(transformer.runTransform(tokens, query));
return generate(transformer.runTransform(tokens, config));
}

function SVGInlineLoader(content) {
Expand All @@ -56,7 +62,13 @@ function SVGInlineLoader(content) {
// Configuration
var query = loaderUtils.parseQuery(this.query);

return "module.exports = " + JSON.stringify(getExtractedSVG(content, query));
var extractedSVG = getExtractedSVG(content, query);

if (query.raw) {
return extractedSVG;
} else {
return "module.exports = " + JSON.stringify(extractedSVG);
}
}

SVGInlineLoader.getExtractedSVG = getExtractedSVG;
Expand Down
12 changes: 6 additions & 6 deletions karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,28 @@ var webpackConf = {
loaders: [
{
test: /\.json$/,
loaders: ['json'],
},
loaders: ['json']
}
]
},
entry: [
'./index.js'
],
resolve: {
extensions: ["", ".js", ".jsx"],
},
}
};

module.exports = function(config) {
var conf = {
basePath: '.',
frameworks: ['mocha'],
files: [
'./tests/**/*.js',
'./tests/**/*.js'
],
exclude: [],
preprocessors: {
'./tests/**/*.js': ['webpack'],
'./tests/**/*.js': ['webpack']
},
reporters: ['spec'],
port: 9876,
Expand All @@ -39,7 +39,7 @@ module.exports = function(config) {
'karma-spec-reporter',
'karma-mocha',
'karma-chrome-launcher',
'karma-webpack',
'karma-webpack'
],
webpack: webpackConf,
autoWatch: true,
Expand Down
7 changes: 7 additions & 0 deletions lib/conditions.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,18 @@ function createHasNoAttributes(attributes) {
}
}

function createHasAttributes(attributes) {
return function hasAttributes(attributeToken) {
return attributes.indexOf(attributeToken[0]) > -1;
}
}

module.exports = {
isSVGToken: isSVGToken,
isStyleToken: isStyleToken,
isFilledObject: isFilledObject,
hasNoWidthHeight: hasNoWidthHeight,
createHasNoAttributes: createHasNoAttributes,
createHasAttributes: createHasAttributes,
isStartTag: isStartTag
};
Loading