浏览器中使用react+jsx

本文介绍了如何在不使用webpack的条件下,通过`npm`安装React和Babel,实现简单的Like按钮组件,并探讨了`import`和`require`在React中的使用问题。作者还展示了如何解决`import`时的`exports`和`require`引用错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开始学react,先只在浏览器处理,结合jsx,简单点,不搞webpack等预处理。

先安装react,我的版本18.1.0:

npm install -g react
npm install -g react-dom

再安装babel,我的版本7.17.11。通天塔,很牛的样子,要把上帝搞乱的语言重新统一起来,负责解析jsx文件:

npm install -g @babel/standalone

写一个like_button.jsx文件:

'use strict';

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }

  render() {
    if (this.state.liked) {
      return 'You liked this.';
    }

    return (
      <button onClick={() => this.setState({ liked: true })}>
        Like2
      </button>
    );
  }
}
export default LikeButton;

写一个index.html文件,通过script标签加载like_button.jsx:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Add React in One Minute</title>
  </head>
  <body>

    <h2>Add React in One Minute</h2>
    <p>This page demonstrates using React with no build tooling.</p>
    <p>React is loaded as a script tag.</p>

    <!-- We will put our React component inside this div. -->
    <div id="container"></div>

    <!-- Load React. -->
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <script src="js/react.development.js"></script>
    <script src="js/react-dom.development.js"></script>
    <script src="js/babel.min.js"></script>

    <script type="text/babel" src="src/like_button.jsx"></script>
    <script type="text/babel">
      const domContainer = document.querySelector('#container');
      const root = ReactDOM.createRoot(domContainer);
      root.render(React.createElement(LikeButton));
    </script>
  </body>
</html>

主要是script标签要加type='text/babel',告诉babel来解析。

如果不用script加载,用import呢,因为有多个jsx文件时,你总想用模组化,而不是一开始就让html把全部jsx文件加载了,试试:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Add React in One Minute</title>
  </head>
  <body>

    <h2>Add React in One Minute</h2>
    <p>This page demonstrates using React with no build tooling.</p>
    <p>React is loaded as a script tag.</p>

    <!-- We will put our React component inside this div. -->
    <div id="container"></div>

    <!-- Load React. -->
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <script src="js/react.development.js"></script>
    <script src="js/react-dom.development.js"></script>
    <script src="js/babel.min.js"></script>

    <script type="text/babel">
      import LikeButton from './src/like_button.jsx';
      const domContainer = document.querySelector('#container');
      const root = ReactDOM.createRoot(domContainer);
      root.render(React.createElement(LikeButton));
    </script>
  </body>
</html>

报错:Uncaught ReferenceError: require is not defined

看起来是babel加载文件时用到了require函数,给它一个:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Add React in One Minute</title>
  </head>
  <body>

    <h2>Add React in One Minute</h2>
    <p>This page demonstrates using React with no build tooling.</p>
    <p>React is loaded as a script tag.</p>

    <!-- We will put our React component inside this div. -->
    <div id="container"></div>

    <!-- Load React. -->
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <script src="js/react.development.js"></script>
    <script src="js/react-dom.development.js"></script>
    <script src="js/babel.min.js"></script>
    <script>
      window.require=function(module){
          let xhr = new XMLHttpRequest();
          xhr.open("GET", module, false);
          xhr.send();
          if(xhr.status != 200) {
            throw new Error("require error: http status " + xhr.status);
          }
          //console.log(xhr.responseText);
          //console.log(Babel);
          let code = Babel.transform(xhr.responseText,{presets: ['es2015','react']}).code;
          //console.log(code); 
          let obj=eval(code);
          //console.log(obj);
          return obj;
      }
    </script>
    <script type="text/babel">
      import LikeButton from './src/like_button.jsx';
      const domContainer = document.querySelector('#container');
      const root = ReactDOM.createRoot(domContainer);
      root.render(React.createElement(LikeButton));
    </script>
  </body>
</html>

之前错误没了,报新的错误:Uncaught ReferenceError: exports is not defined

继续hook的方式挂载:

    <script>
      //用hook模式支持jsx文件中的exports
      window.exports = window;
      window.require=function(module){
          let xhr = new XMLHttpRequest();
          xhr.open("GET", module, false);
          xhr.send();
          if(xhr.status != 200) {
            throw new Error("require error: http status " + xhr.status);
          }
          //console.log(xhr.responseText);
          //console.log(Babel);
          let code = Babel.transform(xhr.responseText,{presets: ['es2015','react']}).code;
          //console.log(code); 
          let obj=eval(code);
          //console.log(obj);
          return obj;
      }
    </script>

ok,可以了。

require要求同步方法,应该没办法用浏览器的fetch函数?

import的js或jsx文件超过500k,babel会报错:[BABEL] Note: The code generator has deoptimised the styling of undefined as it exceeds the max of 500KB.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

火星牛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值