Skip to content

Commit

Permalink
feat: implement basic react tech stack
Browse files Browse the repository at this point in the history
  • Loading branch information
PeachScript committed Aug 8, 2022
1 parent 51a3a3e commit 3a6791d
Show file tree
Hide file tree
Showing 4 changed files with 237 additions and 12 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"trailingComma": "all"
},
"dependencies": {
"@swc/core": "^1.2.224",
"@types/hast": "^2.3.4",
"@umijs/core": "^4.0.9",
"estree-util-to-js": "^1.1.0",
Expand Down
172 changes: 161 additions & 11 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion src/features/compile.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import ReactTechStack from '@/techStacks/react';
import type { IApi } from '@/types';

export default (api: IApi) => {
api.chainWebpack((memo) => {
// register react tech stack by default
api.registerTechStack(() => new ReactTechStack());

// configure loader to compile markdown
api.chainWebpack(async (memo) => {
const babelInUmi = memo.module.rule('src').use('babel-loader').entries();

memo.module
Expand Down
69 changes: 69 additions & 0 deletions src/techStacks/react.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import type { IDumiTechStack } from '@/types';
import {
transformSync,
type ExportDefaultDeclaration,
type ExportDefaultExpression,
type ModuleDeclaration,
} from '@swc/core';
import Visitor from '@swc/core/Visitor';

/**
* swc plugin for replace export to return
*/
class ReactDemoVisitor extends Visitor {
visitExportDefaultDeclaration(
n: ExportDefaultDeclaration,
): ModuleDeclaration {
return {
type: 'ReturnStatement',
span: n.span,
argument: n.decl,
} as any;
}

visitExportDefaultExpression(n: ExportDefaultExpression): ModuleDeclaration {
return {
type: 'ReturnStatement',
span: n.span,
argument: n.expression,
} as any;
}
}

export default class ReactTechStack implements IDumiTechStack {
name = 'react';

isSupported(...[, lang]: Parameters<IDumiTechStack['isSupported']>) {
return ['jsx', 'tsx'].includes(lang);
}

transformCode(...[raw, opts]: Parameters<IDumiTechStack['transformCode']>) {
if (opts.type === 'code-block') {
const isTSX = opts.fileAbsPath.endsWith('.tsx');
const { code } = transformSync(raw, {
jsc: {
parser: {
syntax: isTSX ? 'typescript' : 'ecmascript',
[isTSX ? 'tsx' : 'jsx']: true,
},
target: 'es2022',
},
module: {
// all imports to require
type: 'commonjs',
// no __esModule flag
importInterop: 'none',
// no 'use strict'
strictMode: false,
},
plugin: (m) => new ReactDemoVisitor().visitProgram(m),
});

return `(function () {
${code}
})()`;
}

return raw;
}
}

0 comments on commit 3a6791d

Please sign in to comment.