浏览器内可以加载外部库吗?

时间:2018-07-07 15:48:03

标签: javascript reactjs

在浏览器中加载react时,我无法“ npm install”一个库,然后将其包含在我的react代码中,

var somelibrary = require('somelibrary');

我想知道如何在浏览器中做到这一点,就像加载加载后只运行源文件一样简单。像

<script src="somereactlibrary.js"></script>

还是图书馆有很多文件/依赖关系,这不会那么简单吗? (如果该库只是一个文件,那该怎么办?在技术上可行吗?)

这是来自reactjs.org的代码,用于在浏览器中进行反应:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

    <!-- Don't use this in production: -->
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">

      ReactDOM.render(
        <h1>Hello, world!</h1>,
        document.getElementById('root')
      );

    </script>
    <!--
      Note: this page is a great way to try React but it's not suitable for production.
      It slowly compiles JSX with Babel in the browser and uses a large development build of React.

      Read this section for a production-ready setup with JSX:
      http://reactjs.org/docs/add-react-to-a-website.html#add-jsx-to-a-project

      In a larger project, you can use an integrated toolchain that includes JSX instead:
      http://reactjs.org/docs/create-a-new-react-app.html

      You can also use React without JSX, in which case you can remove Babel:
      https://reactjs.org/docs/react-without-jsx.html
    -->
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

要在浏览器中呈现React,您需要reactreact-dom库。如果您无权将所有代码捆绑在一起的构建步骤,则可以像您说的那样将其他库作为单独的脚本标签加载。

示例

ReactDOM.render(
  React.createElement('div', {}, moment().format('YYYY-MM-DD')),
  document.getElementById('root')
);
<script src="https://unpkg.com/moment@2.22.2/moment.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>
<div id="root"></div>