Created
July 5, 2017 18:57
-
-
Save vamsiampolu/1686527cb352da5579df300e44c4e9e9 to your computer and use it in GitHub Desktop.
Svg Sprite Loader runtime generator for React Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path'); | |
const pascalCase = require('pascal-case'); | |
const { stringifyRequest } = require('loader-utils'); | |
const { stringifySymbol, stringify } = require('../../lib/utils'); | |
module.exports = function runtimeGenerator({ 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} />; | |
} | |
} | |
`; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
module: { | |
rules: [ | |
{ | |
test: /\.svg$/, | |
use: [ | |
{ | |
loader: 'svg-sprite-loader', | |
options: { | |
runtimeGenerator: require.resolve('./svg-to-icon-component-runtime-generator'), | |
runtimeOptions: { | |
iconModule: './icon.jsx' // Relative to current build context folder | |
} | |
} | |
} | |
] | |
} | |
] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@vamsiampolu should
require.resolve('./svg-to-icon-component-runtime-generator')
berequire.resolve('./svg-to-react-component')
instead?Trying to trace the meaning of the path here and where the file should live