AI写作智能体 自主规划任务,支持联网查询和网页读取,多模态高效创作各类分析报告、商业计划、营销方案、教学内容等。 广告
[TOC] ## 参考链接 [https://www.jianshu.com/p/e79ac021ce56](https://www.jianshu.com/p/e79ac021ce56) ## babel文档 [https://babeljs.io/docs/en/next/babel-preset-react#via-babelrc-recommended-](https://babeljs.io/docs/en/next/babel-preset-react#via-babelrc-recommended-) ## 使用详情 ### 安装相关依赖 - 安装babel ``` npm i babel-loader@8.0.0-beta.0 @babel/core @babel/preset-env @babel/plugin-transform-runtime @babel/preset-react -D npm i @babel/polyfill @babel/runtime -D ``` 模块作用: - `@babel/core` babel核心; - `@babel/preset-env` 编译ES6; - `@babel/preset-react` 转换JSX; - `@babel/plugin-transform-runtime` 避免 polyfill污染全局变量,减小打包体积 - `@babel/polyfill:` ES6 内置方法和函数转化垫片 ### 创建`.babelrc`,并配置`.babelrc`文件 ```javascript { "presets": ["@babel/preset-env", "@babel/preset-react"], "plugins": ["@babel/plugin-transform-runtime"] } ``` ### 定义jsx解析方法 parseJsx.js ``` function render(vnode) { if(!vnode){ return null; } // Strings just convert to #text Nodes: if (vnode.split) return document.createTextNode(vnode); // create a DOM element with the nodeName of our VDOM element: let n = document.createElement(vnode.nodeName); // copy attributes onto the new node: let a = vnode.attributes || {}; Object.keys(a).forEach(k => n.setAttribute(k, a[k])); // render (build) and then append child nodes: (vnode.children || []).forEach(c => n.appendChild(render(c))); return n; } function parseJsx(nodeName, attributes, ...args) { let children = args.length ? [].concat(...args) : null; return { nodeName, attributes, children }; } export { parseJsx, render } ``` ### 修改`.babelrc`自定义解析函数 ``` { "presets": [ "@babel/preset-env", [ "@babel/preset-react", { "pragma": "dom", // 处理jsx的方法 默认 React.createElement "pragmaFrag": "DomFrag", // 这个好像没用到 default is React.Fragment "throwIfNamespace": false // defaults to true } ] ], "plugins": [ "@babel/plugin-transform-runtime", "@babel/plugin-syntax-jsx" ] } ``` ### 使用jsx ```jsx import { parseJsx, render } from './parseJsx.js' const dom = parseJsx; //解析方法 //内容 let nodes = <div class="zoo-popup zoo-popup-container-center"> <div class="zoo-popup-confirm"> <p>消息</p> <div class="btns"> <button class="mulo-cancel">取消</button> <button class="mulo-success">确认</button> </div> </div> </div> //主题内容 let toastBody = render(nodes); //显示内容 window.document.body.appendChild(toastBody); ```