Javascript 如何使用cdn在html中加载es6,react,babel代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43931538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:15:18  来源:igfitidea点击:

How to load es6, react, babel code in html with cdn?

javascriptreactjsbabeljs

提问by anoop chandran

I have Codepencode that I'm trying to replicate on an web page using just three files, index.html, main.js, and style.css. I tried loading these scripts on the head tag of HTML file.

我有Codepen代码,我试图仅使用三个文件 index.html、main.js 和 style.css 在网页上复制这些代码。我尝试在 HTML 文件的 head 标签上加载这些脚本。

<script src="https://npmcdn.com/[email protected]/dist/btib.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.min.js"></script>

However, it's not working. All I get is this error

但是,它不起作用。我得到的只是这个错误

Uncaught SyntaxError: Unexpected token <

what are necessary CDN script files to load this react-code to HTML?

将此反应代码加载到 HTML 所需的 CDN 脚本文件是什么?

回答by Mayank Shukla

You need to use babel standalonescript to transcompile the code, and you need to include the script for react and react-dom, use these it will work:

您需要使用babel standalone脚本来转编译代码,并且您需要包含用于 的脚本react and react-dom,使用这些它将起作用:

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Reason why it is working with codepen:check the setting/javascript, there you will find the babel is selected as JavaScript Preprocessor, codepen is including the script automatically, but to run these files locally you need to include the standalone script.

它与 codepen 一起工作的原因:检查设置/javascript,你会发现 babel 被选为JavaScript Preprocessor,codepen 自动包含脚本,但要在本地运行这些文件,你需要包含standalone script.

Update:

更新:

1- You need to define the script after the div in which you are rendering the react code, otherwise it will throw the error. like this:

1- 您需要在渲染反应代码的 div 之后定义脚本,否则会抛出错误。像这样:

<body> 
   <div id="root"></div> 
   <script type="text/babel" src="pomodoro.js"></script>
</body>

2- Use ReactDOM.renderinstead of React.render.

2- 使用ReactDOM.render代替React.render

Check the working code:

检查工作代码:

<html>

<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js'></script>
</head>
<body>
   <div id='root'></div>
   <script type='text/babel'>
       class SetTimer extends React.Component{    
  render(){
    return (   
      <div className="set-timer">work <br/> session         
          <div className="minus-add">
            <button className="setting-button" id="minus-timer" onClick={this.props.minus}>-</button>
            <button className="setting-button" id="add-timer" onClick={this.props.add}>+</button>
          </div>
      </div>
    );
  }
} 

class SetBreak extends React.Component{
  
  render(){
    return (   
      <div className="set-break"> break<br/> session 
          <div className="minus-add">
            <button className="setting-button" id="minus-break" onClick={this.props.minusbreak}>-</button>
            <button className="setting-button" id="add-break" onClick={this.props.addbreak}>+</button>
          </div>
      </div>
    );
  }
} 

const leftPad = (time)=>{
  return (time<10)? '0'+time :time
}
const TimerDisplay = (props) => (   
  <div className="timer-display"><span className="worklabel">Work session time</span><br/>
      {props.currentTime}
      <div className="breaktime"><span className="breaklabel">break session time</span><br/>{props.breakTime}</div>
    </div>
);
// let baseTime= 25;
class App extends React.Component {
  constructor(){
    super();
    this.state = {
      baseTime:25,
      breakTime:5,
      currentTime: moment.duration(25,'minutes'),
      timer:null,
      startbuttonvisible:true,
      pausebuttonvisible:false,
      resumebuttonvisible:false,
      stopbuttonvisible:false,
    }
    this.minus =this.minus.bind(this);
    this.add =this.add.bind(this);
    this.minusbreak =this.minusbreak.bind(this);
    this.addbreak =this.addbreak.bind(this);
    this.startTimer = this.startTimer.bind(this);
    this.pauseTimer = this.pauseTimer.bind(this);
    this.resumeTimer = this.resumeTimer.bind(this);
    this.stopTimer = this.stopTimer.bind(this);
    this.reduceTimer = this.reduceTimer.bind(this);
    
  }
  add(){
    this.setState({
      baseTime:this.state.baseTime+1
    });
  }
  minus(){
    this.setState({
      baseTime:this.state.baseTime-1
    });
  }
  addbreak(){
    this.setState({
      breakTime:this.state.breakTime+1
    });
  }
  minusbreak(){
    this.setState({
      breakTime:this.state.breakTime-1
    });
  }
  startTimer(){
    this.setState({
      timer: setInterval(this.reduceTimer, 1000), 
      startbuttonvisible:false,
      pausebuttonvisible:true,
      stopbuttonvisible:true,
    });    
  }
  pauseTimer(){
    clearInterval(this.state.timer);
    this.setState({      
      pausebuttonvisible:false,
      resumebuttonvisible:true,
    });    
  }
  resumeTimer(){
    this.setState({
      timer: setInterval(this.reduceTimer, 1000), 
      startbuttonvisible:false,
      pausebuttonvisible:true,
      stopbuttonvisible:true,
      resumebuttonvisible:false,
    }); 
  }
  stopTimer(){
    clearInterval(this.state.timer);
    this.setState({
      baseTime:25,
      timer: null, 
      startbuttonvisible:true,
      pausebuttonvisible:false,
      stopbuttonvisible:false,
      resumebuttonvisible:false,
    });  
  }
  reduceTimer(){ 
    if(this.state.baseTime === 0) return;
    const newTime = this.state.baseTime - 1;
    this.setState({
      baseTime: newTime,
    });
  }
  render() {
    
    return (
      <div className="container">
         <div className="timebox">
            <div className="header">
                    Pomodoro Clock
            </div>
            <TimerDisplay currentTime={this.state.baseTime} breakTime={this.state.breakTime}/>
            <div id="action-title">
                <small>SETTINGS</small>
            </div>
            <div className="actions">
              <SetTimer minus={this.minus} add={this.add}/>
              <SetBreak minusbreak={this.minusbreak} addbreak={this.addbreak}/>
            </div>
           <div className="timer-control">
            {this.state.startbuttonvisible ? <button id="start-timer" onClick={this.startTimer}>
                START
            </button> : null}
           {this.state.pausebuttonvisible ? <button id="pause-timer" onClick={this.pauseTimer}>
                PAUSE
            </button>: null}
           {this.state.resumebuttonvisible ? <button id="resume-timer" onClick={this.resumeTimer}>
                RESUME
            </button>: null}
           {this.state.stopbuttonvisible ? <button id="stop-timer" onClick={this.stopTimer}>
                STOP
            </button>: null}
           </div>
        </div>
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

   </script>
</body>
</html>

回答by duhaime

Here's a simpler example for the minimalists in the room:

这是房间里极简主义者的一个更简单的例子:

<!DOCTYPE html>
<html>
  <head>
    <meta charset='UTF-8'>
    <title>Minimal Static React</title>
    <script src='https://unpkg.com/[email protected]/umd/react.production.min.js'></script>
    <script src='https://unpkg.com/[email protected]/umd/react-dom.production.min.js'></script>
    <script src='https://unpkg.com/[email protected]/babel.js'></script>
  </head>
  <body>
    <div id='root'></div>

    <script type='text/babel'>
      class App extends React.Component {
        constructor(props) {
          super(props)
          this.state = {count: 1}
          this.increase = this.increase.bind(this)
          this.decrease = this.decrease.bind(this)
        }

        increase() {
          this.setState({'count': this.state.count+1})
        }

        decrease() {
          this.setState({'count': this.state.count-1})
        }

        render() {
          return (
            <div>
              <h1>Count: { this.state.count }</h1>
              <div onClick={this.increase}>+</div>
              <div onClick={this.decrease}>-</div>
            </div>
          )
        }
      }

      ReactDOM.render(<App />, document.querySelector('#root'));
    </script>
  </body>
</html>

回答by Purkhalo Alex

You have to provide appropriate scripts to support React and ES6+, mentioned below:

您必须提供适当的脚本来支持 React 和 ES6+,如下所述:

Finally let's summarize mentioned above with simple .htmlexample

最后让我们用一个简单的.html例子来总结上面提到的

<html>
<head>
    <!-- https://reactjs.org/docs/cdn-links.html -->
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <!-- https://babeljs.io/docs/en/next/babel-standalone.html -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
    <div id="react-container"></div>
    <script type="text/babel">
        const App = () => <div>Hello!</div>
        ReactDOM.render(
        <App />, document.getElementById('react-container'))
    </script>
</body>
</html>

回答by ASHISH RANJAN

<head>
<title>Beginner's Guide to React</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js">       </script>
<script src="https://unpkg.com/[email protected]/babel.js"></script>

<script type="text/babel">
    const rootElement = document.getElementById('root');

     const element = React.createElement('div',{className:''},'Hello World' );

     ReactDOM.render(element, rootElement);

</script>