小编典典

如果index.html在本地提供,可以使用babel-standalone吗?(无网络服务器)

reactjs

在我开始问题之前,这是我已经知道的避免相同答案的信息。

TL; DR: 我已经知道我可以使用网络服务器并将index.html用作http:// localhost:8081 /
index.html
,它将可以正常工作。

现在查看问题详细信息:

我创建了一个最小的react-js应用程序,在index.html文件中引用babel-standalone,如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Minimal</title>
</head>
<body>
    <div id='divRootComponent'></div>

    <!-- react reasonably latest for oct/2018 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.2/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.2/umd/react-dom.production.min.js"></script>

    <!-- babel -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>

    <!-- react CUSTOM component.. i.e. myApp's entry point -->
    <script type="text/babel" src="index.js"></script>
</body>
</html>

并且index.js的内容是:

class YoSupComponent extends React.Component {

  constructor () {
    super();

    this.state = {
      message: 'whatever...'
    };
  }


  componentDidMount() {
    console.log('YoSupComponent.componentDidMount');
  }

  render () {

    return (
      <div>
        Yo ! Dude or Dudette... sup ?
      </div>
    );
  }
}

const props = {}; //none for now...
ReactDOM.render(<YoSupComponent {...props} />
  , document.getElementById('divRootComponent'))

当我尝试通过file:///path/to/index.html访问浏览器中的index.html文件时,错误是:

通过CORS策略已阻止从源“ null”访问“ file:///
D:/path/to/index.js”处的XMLHttpRequest:仅协议方案支持跨源请求:http,数据,chrome,chrome
-扩展名,https。@ babel.min.js:24

因此,认为问题与远程引用文件的脚本标签有关,我在本地下载react和babel,并使引用成为本地文件;然后我再次访问file:///path/to/index.html。

还是会得到同样的错误!这是怎么回事?a)当babel.js文件现在位于本地时,为什么babel甚至甚至使用XMLHttpRequest(根据错误消息)?b)为什么没有这样的反应文件消息?


阅读 381

收藏
2020-07-22

共1个答案

小编典典

根据MDN,如果您指定的脚本标记的类型不是text/javascript,则浏览器将忽略该标记:

嵌入式内容被视为浏览器不会处理的数据块。开发人员必须使用不是JavaScript MIME类型的有效MIME类型来表示数据块。src属性将被忽略。

换句话说,index.js在您的示例中,浏览器不会加载或运行。这是有道理的-如果确实如此,则将出现语法错误,因为您的浏览器无法理解JSX。

实际发生的是该babel-standalone脚本查看您的HTML,找到所有标记的脚本标签text/babel
通过加载它们XMLHttpRequest,然后编译并运行它们。

这就是为什么您会收到CORS错误的原因-浏览器未加载文件,脚本正在加载。不幸的是,我认为如果不使用Web服务器或提前编译Babel代码就无法解决此问题。

2020-07-22