Skip to content

Instantly share code, notes, and snippets.

@marc-rutkowski
Created January 10, 2018 11:14
Show Gist options
  • Save marc-rutkowski/895063ca61e621a4a88b9ad9133790c1 to your computer and use it in GitHub Desktop.
Save marc-rutkowski/895063ca61e621a4a88b9ad9133790c1 to your computer and use it in GitHub Desktop.
Custom Jest transformer for SVG files
/**
* Custom Jest transformer for SVG files
* Replace SVG file contents by a pseudo <svg /> JSX element containing only a data-filename attribute
*
* To make this work with Jest you need to update your Jest configuration with this:
* "transform": {
* "^.+\\.js$": "babel-jest",
* "^.+\\.svg$": "path/to/svg-transform.js"
* }
*
* Ref: http://facebook.github.io/jest/docs/en/tutorial-react.html#custom-transformers
*/
const path = require('path');
const babel = require('babel-core');
const reactPreset = require('babel-preset-react');
module.exports = {
process(src, filename) {
const code = babel.transform(
`
import React from 'react';
export default () => (<svg data-filename="${path.relative(process.cwd(), filename)}" />);
`,
{
filename,
presets: [reactPreset],
retainLines: true,
}
).code;
return code;
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment