Skip to content

Instantly share code, notes, and snippets.

@saadshahd
Last active August 7, 2017 22:14
Show Gist options
  • Save saadshahd/d2a5a4b1eb163a62f8b4bc8b0b37a7bc to your computer and use it in GitHub Desktop.
Save saadshahd/d2a5a4b1eb163a62f8b4bc8b0b37a7bc to your computer and use it in GitHub Desktop.

Revisions

  1. saadshahd revised this gist Aug 7, 2017. 1 changed file with 18 additions and 0 deletions.
    18 changes: 18 additions & 0 deletions webpack.conf.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    {
    test: /\.svg$/,
    exclude: /node_modules/,
    use: [
    {
    loader: 'babel-loader'
    },
    {
    loader: 'svg-sprite-loader',
    options: {
    runtimeGenerator: require.resolve('./svg-to-icon'),
    runtimeOptions: {
    iconModule: conf.path.src('app/components/icon.js')
    }
    }
    }
    ]
    }
  2. saadshahd created this gist Aug 7, 2017.
    34 changes: 34 additions & 0 deletions svg-to-icon.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    const path = require('path');
    const pascalCase = require('pascal-case');
    const {stringifyRequest} = require('loader-utils');
    const {stringifySymbol, stringify} = require('../../lib/utils');

    module.exports = function ({symbol, config, context, loaderContext}) {
    const {spriteModule, symbolModule, runtimeOptions} = config;
    const compilerContext = loaderContext._compiler.context;

    const iconModulePath = path.resolve(compilerContext, runtimeOptions.iconModule);
    const iconModuleRequest = stringify(
    path.relative(path.dirname(symbol.request.file), iconModulePath)
    );

    const spriteRequest = stringifyRequest({context}, spriteModule);
    const symbolRequest = stringifyRequest({context}, symbolModule);
    const parentComponentDisplayName = 'SpriteSymbolComponent';
    const displayName = `${pascalCase(symbol.id)}${parentComponentDisplayName}`;

    return `
    import React from 'react';
    import SpriteSymbol from ${symbolRequest};
    import sprite from ${spriteRequest};
    import ${parentComponentDisplayName} from ${iconModuleRequest};
    const symbol = new SpriteSymbol(${stringifySymbol(symbol)});
    sprite.add(symbol);
    export default class ${displayName} extends React.Component {
    render() {
    return <${parentComponentDisplayName} glyph="${symbol.id}" {...this.props} />;
    }
    }
    `;
    };