fileTransform.js 1.22 KB
Newer Older
zhanghaozhe committed
1
"use strict"
2

zhanghaozhe committed
3 4
const path = require("path")
const camelcase = require("camelcase")
5 6 7 8 9 10

// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html

module.exports = {
  process(src, filename) {
zhanghaozhe committed
11
    const assetFilename = JSON.stringify(path.basename(filename))
12 13

    if (filename.match(/\.svg$/)) {
zhanghaozhe committed
14 15 16 17
      // Based on how SVGR generates a component name:
      // https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
      const pascalCaseFilename = camelcase(path.parse(filename).name, {
        pascalCase: true,
zhanghaozhe committed
18 19
      })
      const componentName = `Svg${pascalCaseFilename}`
20 21 22 23
      return `const React = require('react');
      module.exports = {
        __esModule: true,
        default: ${assetFilename},
zhanghaozhe committed
24 25 26 27 28 29 30 31 32 33 34
        ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
          return {
            $$typeof: Symbol.for('react.element'),
            type: 'svg',
            ref: ref,
            key: null,
            props: Object.assign({}, props, {
              children: ${assetFilename}
            })
          };
        }),
zhanghaozhe committed
35
      };`
36 37
    }

zhanghaozhe committed
38
    return `module.exports = ${assetFilename};`
39
  },
zhanghaozhe committed
40
}