From b89279fc17865944737a673304c6b6e0c11656fd Mon Sep 17 00:00:00 2001 From: jaywcjlove <398188662@qq.com> Date: Mon, 3 Apr 2023 13:36:50 +0800 Subject: [PATCH] fix(jest): fix convert svg file import issue. --- packages/jest/src/transform/file.ts | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/packages/jest/src/transform/file.ts b/packages/jest/src/transform/file.ts index e76bae5f..a5e2c5cb 100644 --- a/packages/jest/src/transform/file.ts +++ b/packages/jest/src/transform/file.ts @@ -1,10 +1,35 @@ import path from 'path'; -// import camelcase from 'camelcase'; +import camelcase from 'camelcase'; // This is a custom Jest transformer turning file imports into filenames. // http://facebook.github.io/jest/docs/en/webpack.html export default { process(sourceText: string, sourcePath: string, options: any) { + const assetFilename = JSON.stringify(path.basename(sourcePath)); + if (sourcePath.match(/\.svg$/)) { + // 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(sourcePath).name, { + pascalCase: true, + }); + const componentName = `Svg${pascalCaseFilename}`; + return `const React = require('react'); + module.exports = { + __esModule: true, + default: ${assetFilename}, + 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} + }) + }; + }), + };`; + } return { code: `module.exports = ${JSON.stringify(path.basename(sourcePath))};`, };