Skip to content

Commit

Permalink
调用babel转换jsx语法的代码抽离成独立的函数
Browse files Browse the repository at this point in the history
  • Loading branch information
magicodex committed Oct 20, 2023
1 parent 7657f6c commit 2848c76
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 25 deletions.
27 changes: 3 additions & 24 deletions bin/render-to-html-string.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
"use strict";

var fs = require('fs');
var babelCore = require('@babel/core');
var reactDOMServer = require('react-dom/server');
var beautifyJs = require('js-beautify/js').js;
var transformJsxToJs = require('./transform-jsx-to-js');

module.exports = renderToHtmlString;

Expand All @@ -26,30 +25,10 @@ function renderToHtmlString(jsxContent, options) {
var deleteTempFile = !(options.deleteTempFile === false);

// 转换 JSX 成 JS 脚本
var transformResult = babelCore.transformSync(jsxContent, {
"presets": [
[
"@babel/preset-react",
{
"pragma": "React.createElement",
"pragmaFrag": "React.Fragment",
"throwIfNamespace": true,
"runtime": "classic"
}
]
]
var jsContent = transformJsxToJs(jsxContent, {
prettyFormat: prettyFormat
});

var jsContent = transformResult.code;
// 美化 JS 内容
if (prettyFormat) {
jsContent = beautifyJs(jsContent, {
indent_size: 2,
wrap_line_length: 120,
space_in_empty_paren: true
});
}

// 写入 JS 内容到临时文件
fs.writeFileSync(tempFilePath, jsContent);
// 加载 JS 脚本
Expand Down
48 changes: 48 additions & 0 deletions bin/transform-jsx-to-js.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"use strict";

var babelCore = require('@babel/core');
var beautifyJs = require('js-beautify/js').js;

module.exports = transformJsxToJs;

/**
* @description 转换 jsx 内容成 js 内容
* @param {string} jsxContent
* @param {object} [options]
* @returns {string}
*/
function transformJsxToJs(jsxContent, options) {
if (jsxContent === null || jsxContent === undefined) {
return '';
}

options = (options || {});
var prettyFormat = (options.prettyFormat === true);

// 转换 JSX 成 JS 脚本
var transformResult = babelCore.transformSync(jsxContent, {
"presets": [
[
"@babel/preset-react",
{
"pragma": "React.createElement",
"pragmaFrag": "React.Fragment",
"throwIfNamespace": true,
"runtime": "classic"
}
]
]
});

var jsContent = transformResult.code;
// 美化 JS 内容
if (prettyFormat) {
jsContent = beautifyJs(jsContent, {
indent_size: 2,
wrap_line_length: 120,
space_in_empty_paren: true
});
}

return jsContent;
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "jsx-render-to-html",
"version": "1.1.5",
"version": "1.1.6",
"description": "转换 jsx 文件成 html 文件",
"license": "MIT",
"author": "mh.z",
Expand Down

0 comments on commit 2848c76

Please sign in to comment.