Skip to content

Commit

Permalink
feat(config): Add .processCode config as a hook for complex usecases
Browse files Browse the repository at this point in the history
  • Loading branch information
jesstelford committed Sep 15, 2022
1 parent 1b996eb commit 38b6285
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
6 changes: 6 additions & 0 deletions README.md
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions lib/defaultModules/processCode.js
@@ -0,0 +1 @@
export default (code) => code;
3 changes: 3 additions & 0 deletions lib/makeWebpackConfig.js
Expand Up @@ -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: {
Expand Down
14 changes: 12 additions & 2 deletions 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(`<React.Fragment>${code.trim() || ''}</React.Fragment>`, {
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(`<React.Fragment>${processedCode.trim()}</React.Fragment>`, {
presets: ['react'],
}).code;
};

export const validateCode = (code: string) => {
try {
Expand Down

0 comments on commit 38b6285

Please sign in to comment.