UNPKG

react-cosmos

Version:

Sandbox for developing and testing UI components in isolation

58 lines (54 loc) 2.49 kB
import { flatten } from 'lodash-es'; import { createImportMap, importPath, sortedImportKeys, } from './shared.js'; export function userImportsTemplate({ globalImports, modulePaths: { fixturePaths, decoratorPaths }, rendererConfig, rootDir, relativeToDir, typeScript, }) { function ext(filePath) { // Add compat with projects where allowImportingTsExtensions isn't enabled return typeScript ? filePath.replace(/\.tsx?$/, '') : filePath; } function ts(annotation) { return typeScript ? annotation : ''; } const globalImportItems = globalImports.map(p => `import '${ext(importPath(p, relativeToDir))}';`); const fixtures = createImportMap(fixturePaths, rootDir, relativeToDir); const fixtureKeys = sortedImportKeys(fixtures); const fixtureImports = fixtureKeys.map((k, i) => `import * as fixture${i} from '${ext(fixtures[k])}';`); const fixtureItems = fixtureKeys.map((k, i) => ` '${k}': { module: fixture${i} }`); const decorators = createImportMap(decoratorPaths, rootDir, relativeToDir); const decoratorKeys = sortedImportKeys(decorators); const decoratorImports = decoratorKeys.map((k, i) => `import * as decorator${i} from '${ext(decorators[k])}';`); const decoratorItems = decoratorKeys.map((k, i) => ` '${k}': { module: decorator${i} }`); const rendererConfigStr = JSON.stringify(rendererConfig, null, 2); let importGroups = [globalImportItems, fixtureImports, decoratorImports]; if (typeScript) { importGroups.unshift([ `import type { RendererConfig, UserModuleWrappers } from 'react-cosmos-core';`, ]); } return ` // NOTE: This file is auto-generated by React Cosmos. // It imports all fixture and decorator modules, making them available to the // React Cosmos renderer along with the renderer config. ${importsStr(importGroups)} export const rendererConfig${ts(': RendererConfig')} = ${rendererConfigStr}; const fixtures = {${objBody(fixtureItems)}}; const decorators = {${objBody(decoratorItems)}}; export const moduleWrappers${ts(': UserModuleWrappers')} = { lazy: false, fixtures, decorators }; `.trimStart(); } function importsStr(items) { if (flatten(items).length === 0) { return ''; } const str = items .filter(rows => rows.length > 0) .map(rows => rows.join('\n')) .join('\n\n'); return `\n${str}\n`; } function objBody(items) { return items.length > 0 ? `\n${items.join(`,\n`)}\n` : ''; }