svg-sprite-generation-loader 0.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "env": {
3
+ "commonjs": true,
4
+ "es2021": true,
5
+ "node": true
6
+ },
7
+ "extends": ["airbnb-base", "prettier"],
8
+ "parserOptions": {
9
+ "ecmaVersion": "latest"
10
+ },
11
+ "rules": {}
12
+ }
@@ -0,0 +1,11 @@
1
+ # To get started with Dependabot version updates, you'll need to specify which
2
+ # package ecosystems to update and where the package manifests are located.
3
+ # Please see the documentation for all configuration options:
4
+ # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
5
+
6
+ version: 2
7
+ updates:
8
+ - package-ecosystem: "npm" # See documentation for possible values
9
+ directory: "/" # Location of package manifests
10
+ schedule:
11
+ interval: "daily"
@@ -0,0 +1,4 @@
1
+ #!/bin/sh
2
+ . "$(dirname "$0")/_/husky.sh"
3
+
4
+ npx lint-staged
@@ -0,0 +1,4 @@
1
+ {
2
+ "singleQuote": true,
3
+ "trailingComma": "es5"
4
+ }
package/README.md CHANGED
@@ -3,7 +3,50 @@
3
3
  [![npm version](https://img.shields.io/npm/v/svg-sprite-generation-loader)](https://www.npmjs.com/package/svg-sprite-generation-loader)
4
4
  [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/vadymshymko/svg-sprite-generation-loader/blob/master/LICENSE)
5
5
 
6
- Webpack plugin and loader for generating svg sprites
6
+ Webpack loader for generating external svg symbol sprite files
7
+
8
+ ## How it works?
9
+
10
+ svg-sprite-generation-loader is a webpack-loader that takes a multiple svg files, transform them (parse and return as an object with `symbolId`, `attributes` and `content` (disabled by default) keys), optimizes and put them back in one file.
11
+
12
+ Input multiple svg files, e.g:
13
+
14
+ ```html
15
+ <!-- file1.svg -->
16
+ <svg viewBox="0 0 10 10">
17
+ <!-- file1.svg content -->
18
+ </svg>
19
+
20
+ <!-- file2.svg -->
21
+ <svg viewBox="0 0 10 30">
22
+ <!-- file2.svg content -->
23
+ </svg>
24
+
25
+ <!-- file3.svg -->
26
+ <svg viewBox="0 0 15 40">
27
+ <!-- file3.svg content -->
28
+ </svg>
29
+ ```
30
+
31
+ Output one svg file (svg sprite):
32
+
33
+ ```html
34
+ <svg xmlns="http://www.w3.org/2000/svg">
35
+ <symbol viewBox="0 0 10 10" id="file1">
36
+ <!-- file1.svg content -->
37
+ </symbol>
38
+
39
+ <symbol viewBox="0 0 10 30" id="file2">
40
+ <!-- file1.svg content -->
41
+ </symbol>
42
+
43
+ <symbol viewBox="0 0 15 40" id="file3">
44
+ <!-- file3.svg content -->
45
+ </symbol>
46
+ </svg>
47
+ ```
48
+
49
+ You can refer to this file to display all your icons using [SVG stacking technique](https://css-tricks.com/svg-fragment-identifiers-work/#article-header-id-4)
7
50
 
8
51
  ## Installation:
9
52
 
@@ -17,24 +60,41 @@ npm install svg-sprite-generation-loader --save-dev
17
60
  yarn add svg-sprite-generation-loader --dev
18
61
  ```
19
62
 
63
+ ## Options
64
+
65
+ Plugin options:
66
+
67
+ | Name | Type | Default value | Description |
68
+ | -------------- | -------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------- |
69
+ | spriteFilePath | `string` | `sprite.svg` | Path to sprite file.<br /> `webpack.output.path` <br /> is included |
70
+ | svgo | object | default preset with disabled `removeUselessDefs`, `removeViewBox` and `cleanupIDs` plugins | [svgo](https://github.com/svg/svgo) config object |
71
+
72
+ Loader options:
73
+
74
+ | Name | Type | Default value | Description |
75
+ | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
76
+ | symbolId | `string`&nbsp;\|&nbsp;`function(iconPath)` - function that takes the file path of the original icon as an argument and returns the symbolId value<br /> In both cases you can use [interpolateName](https://github.com/webpack/loader-utils#interpolatename) patterns | `"[name]"` which is equal to icon filename (without extension). For example, by default symbolId for `file1.svg` file will be `file1` | `<symbol>`&nbsp;`id` attribute value. |
77
+ | addContent | `boolean` | `false` | Add svg content as property to transformed svg object (may increase bundle size when enabled) |
78
+ | attributes | `string[]` | | What attributes of the original svg need to be added to transformed svg object (By default - all) |
79
+
20
80
  ## Usage:
21
81
 
22
82
  In your webpack config:
23
83
 
24
84
  ```javascript
25
- const SvgSpriteGenerationPlugin = require("svg-sprite-generation-loader/plugin.js");
85
+ const SvgSpriteGenerationPlugin = require('svg-sprite-generation-loader/plugin.js');
26
86
 
27
87
  module.exports = {
28
88
  plugins: [
29
89
  new SvgSpriteGenerationPlugin.Plugin({
30
- spriteFilePath: `path/to/sprite/file.svg`,
90
+ spriteFilePath: 'path/to/sprite/filename.svg',
31
91
  }),
32
92
  ],
33
93
  module: {
34
94
  rules: [
35
95
  {
36
96
  test: /\.svg$/,
37
- use: "svg-sprite-generation-loader",
97
+ use: 'svg-sprite-generation-loader',
38
98
  },
39
99
  ],
40
100
  },
@@ -43,14 +103,11 @@ module.exports = {
43
103
 
44
104
  In some source code:
45
105
 
46
- ```javascript
47
- import someIcon from 'path/to/iconFileName.svg'
48
-
49
- export default function SomeIcon() {
50
- return (
51
- <svg {...someIcon}>
52
- <use href="path/to/sprite/file.svg#iconFileName">
53
- </svg>
54
- );
55
- }
106
+ ```jsx
107
+ import iconData from 'path/to/some/icon-file-name.svg';
108
+ // by default iconData will include symbolId and attributes keys. If you enable the addContent loader option, the `content` key will also be added
109
+
110
+ <svg {...iconData.attributes}>
111
+ <use href={`path/to/sprite/filename.svg#${iconData.symbolId}`} />
112
+ </svg>;
56
113
  ```
package/index.js CHANGED
@@ -1,17 +1,42 @@
1
- const path = require("path");
1
+ const loaderUtils = require('loader-utils');
2
2
 
3
- const svgSpriteState = require("./utils/spriteState.js");
4
- const parseSvg = require("./utils/parseSvg.js");
3
+ const svgSpriteState = require('./utils/spriteState');
4
+ const transformSvg = require('./utils/transformSvg');
5
5
 
6
- module.exports = function (source) {
7
- const { attributes, content } = parseSvg(source);
8
- const symbolId = path.basename(this.resourcePath, ".svg");
6
+ function svgSpriteGenerationLoader(source) {
7
+ const options = {
8
+ symbolId: '[name]',
9
+ ...this.getOptions(),
10
+ };
9
11
 
10
- if (this.target === "web") {
12
+ const { attributes: parsedAttributes, content } = transformSvg(source);
13
+
14
+ const symbolId = loaderUtils.interpolateName(
15
+ this,
16
+ typeof options.symbolId === 'string'
17
+ ? options.symbolId
18
+ : options.symbolId(this.resourcePath)
19
+ );
20
+
21
+ const attributes = options.attributes
22
+ ? options.attributes.reduce((result, attrName) => {
23
+ // eslint-disable-next-line no-param-reassign
24
+ result[attrName] = parsedAttributes[attrName];
25
+ return result;
26
+ }, {})
27
+ : parsedAttributes;
28
+
29
+ if (this.target === 'web') {
11
30
  svgSpriteState.addSpriteIcon({ symbolId, attributes, content });
12
31
  }
13
32
 
14
33
  return `
15
- export default ${JSON.stringify(attributes)}
34
+ export default ${JSON.stringify({
35
+ symbolId,
36
+ attributes,
37
+ ...(options.addContent ? { content } : {}),
38
+ })}
16
39
  `;
17
- };
40
+ }
41
+
42
+ module.exports = svgSpriteGenerationLoader;
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "svg-sprite-generation-loader",
3
- "version": "0.0.1",
4
- "description": "Webpack loader for generating svg sprites",
3
+ "version": "1.1.0",
4
+ "description": "Webpack loader for generating external svg symbol sprite files",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
7
+ "test": "echo \"Error: no test specified\" && exit 1",
8
+ "prepare": "husky install"
8
9
  },
9
10
  "repository": {
10
11
  "type": "git",
@@ -28,6 +29,20 @@
28
29
  },
29
30
  "homepage": "https://github.com/vadymshymko/svg-sprite-generation-loader#readme",
30
31
  "dependencies": {
32
+ "loader-utils": "^3.2.0",
31
33
  "svgo": "^2.8.0"
34
+ },
35
+ "devDependencies": {
36
+ "eslint": "^7.32.0 || ^8.2.0",
37
+ "eslint-config-airbnb-base": "^15.0.0",
38
+ "eslint-config-prettier": "^8.5.0",
39
+ "eslint-plugin-import": "^2.25.2",
40
+ "husky": ">=6",
41
+ "lint-staged": ">=10",
42
+ "prettier": "^2.6.2"
43
+ },
44
+ "lint-staged": {
45
+ "*.js": "eslint --cache --fix",
46
+ "*.{js,css,md}": "prettier --write"
32
47
  }
33
48
  }
package/plugin.js CHANGED
@@ -1,14 +1,14 @@
1
- const { optimize } = require("svgo");
1
+ const { optimize } = require('svgo');
2
2
 
3
- const svgSpriteState = require("./utils/spriteState.js");
3
+ const svgSpriteState = require('./utils/spriteState');
4
4
 
5
5
  class SvgSpriteGeneratorPlugin {
6
6
  static defaultOptions = {
7
- spriteFilePath: "sprite.svg",
7
+ spriteFilePath: 'sprite.svg',
8
8
  svgo: {
9
9
  plugins: [
10
10
  {
11
- name: "preset-default",
11
+ name: 'preset-default',
12
12
  params: {
13
13
  overrides: {
14
14
  removeUselessDefs: false,
@@ -41,7 +41,7 @@ class SvgSpriteGeneratorPlugin {
41
41
  compilation.hooks.processAssets.tap(
42
42
  SvgSpriteGeneratorPlugin.name,
43
43
  () => {
44
- if (compilation.options.loader.target === "web") {
44
+ if (compilation.options.loader.target === 'web') {
45
45
  compilation.emitAsset(
46
46
  `${this.options.spriteFilePath}`,
47
47
  new RawSource(
@@ -1,4 +1,4 @@
1
- class SvgSpriteGeneratorState {
1
+ class SvgSpriteGenerationState {
2
2
  constructor() {
3
3
  this.spriteIcons = {};
4
4
  }
@@ -8,10 +8,12 @@ class SvgSpriteGeneratorState {
8
8
  }
9
9
 
10
10
  getSpriteContent() {
11
- return `${Object.keys(this.spriteIcons).reduce((result, iconId) => {
12
- return `${result}<symbol viewBox="${this.spriteIcons[iconId].attributes.viewBox}" fill="none" id="${iconId}">${this.spriteIcons[iconId].content}</symbol>`;
13
- }, '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">')}</svg>`;
11
+ return `${Object.keys(this.spriteIcons).reduce(
12
+ (result, iconId) =>
13
+ `${result}<symbol viewBox="${this.spriteIcons[iconId].attributes.viewBox}" fill="none" id="${iconId}">${this.spriteIcons[iconId].content}</symbol>`,
14
+ '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">'
15
+ )}</svg>`;
14
16
  }
15
17
  }
16
18
 
17
- module.exports = new SvgSpriteGeneratorState();
19
+ module.exports = new SvgSpriteGenerationState();
@@ -0,0 +1,25 @@
1
+ function transformSvg(source) {
2
+ const [, parsedAttributes, parsedContent] = source.match(
3
+ /<svg(.{0,})>([\s\S]+)<\/svg>/i
4
+ );
5
+
6
+ const attributes = parsedAttributes
7
+ .match(/([\w-:]+)(=)?("[^<>"]*"|'[^<>']*'|[\w-:]+)/g)
8
+ .reduce((result, attribute) => {
9
+ const [name, unformattedValue] = attribute.split('=');
10
+
11
+ // eslint-disable-next-line no-param-reassign
12
+ result[name] = unformattedValue
13
+ ? unformattedValue.replace(/['"]/g, '')
14
+ : true;
15
+
16
+ return result;
17
+ }, {});
18
+
19
+ return {
20
+ attributes,
21
+ content: parsedContent.replace(/\n/g, ' ').trim(),
22
+ };
23
+ }
24
+
25
+ module.exports = transformSvg;
package/utils/parseSvg.js DELETED
@@ -1,22 +0,0 @@
1
- module.exports = function (source) {
2
- const [_, parsedAttributes, parsedContent] = source.match(
3
- /<svg(.{0,})>([\s\S]+)<\/svg>/i
4
- );
5
-
6
- const attributes = parsedAttributes
7
- .match(/([\w-:]+)(=)?("[^<>"]*"|'[^<>']*'|[\w-:]+)/g)
8
- .reduce(function (result, attribute) {
9
- const [name, unformattedValue] = attribute.split("=");
10
-
11
- result[name] = unformattedValue
12
- ? unformattedValue.replace(/['"]/g, "")
13
- : true;
14
-
15
- return result;
16
- }, {});
17
-
18
- return {
19
- attributes,
20
- content: parsedContent.replace(/\n/g, " ").trim(),
21
- };
22
- };