diff --git a/README.md b/README.md index 6c82bbe3..f05b80b7 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,12 @@ export { themeB } from './themeB'; // etc... ``` +## Additional Code Transformations + +A hook into the internal processing of code is available via the `processCode` option, which is a path to a file that exports a function that receives the code as entered into the editor, and returns the new code to be rendered. + +One example is [wrapping code in an IIFE for state support](https://github.com/seek-oss/playroom/issues/66). + ## TypeScript Support If a `tsconfig.json` file is present in your project, static prop types are parsed using [react-docgen-typescript](https://github.com/styleguidist/react-docgen-typescript) to provide better autocompletion in the Playroom editor. diff --git a/lib/defaultModules/processCode.js b/lib/defaultModules/processCode.js new file mode 100644 index 00000000..7a85f668 --- /dev/null +++ b/lib/defaultModules/processCode.js @@ -0,0 +1 @@ +export default (code) => code; diff --git a/lib/makeWebpackConfig.js b/lib/makeWebpackConfig.js index 56defa7c..1e7cf3b1 100644 --- a/lib/makeWebpackConfig.js +++ b/lib/makeWebpackConfig.js @@ -54,6 +54,9 @@ module.exports = async (playroomConfig, options) => { __PLAYROOM_ALIAS__USE_SCOPE__: playroomConfig.scope ? relativeResolve(playroomConfig.scope) : require.resolve('./defaultModules/useScope'), + __PLAYROOM_ALIAS__PROCESS_CODE__: playroomConfig.processCode + ? relativeResolve(playroomConfig.processCode) + : require.resolve('./defaultModules/processCode'), }, }, module: { diff --git a/package.json b/package.json index 84697000..89c942bb 100644 --- a/package.json +++ b/package.json @@ -50,6 +50,11 @@ "release": { "success": false }, + "jest": { + "moduleNameMapper": { + "^__PLAYROOM_ALIAS__PROCESS_CODE__$": "/lib/defaultModules/processCode" + } + }, "repository": { "type": "git", "url": "https://github.com/seek-oss/playroom.git" diff --git a/src/utils/compileJsx.ts b/src/utils/compileJsx.ts index dadea779..2b0d2e4b 100644 --- a/src/utils/compileJsx.ts +++ b/src/utils/compileJsx.ts @@ -1,9 +1,19 @@ import { transform } from '@babel/standalone'; +/* eslint-disable-next-line import/no-unresolved */ +/* @ts-expect-error: This import is webpack magic */ +import processCode from '__PLAYROOM_ALIAS__PROCESS_CODE__'; -export const compileJsx = (code: string) => - transform(`${code.trim() || ''}`, { +export const compileJsx = (code: string) => { + const processedCode = processCode(code); + + if (typeof processedCode !== 'string') { + throw new Error('processCode function must return a string of code.'); + } + + return transform(`${processedCode.trim()}`, { presets: ['react'], }).code; +}; export const validateCode = (code: string) => { try {