ReactJs - 多个组件 - 错误:未捕获的ReferenceError:未定义require

时间:2016-06-22 09:31:30

标签: javascript reactjs babel

我很反应,我遇到了多个组件的问题。

这是我得到的错误未捕获的ReferenceError:未定义的需求

我正在使用的代码。

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
    <script src="https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-xtf1/t39.3284-6/11057100_835863049837306_1087123501_n.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="app"></div>
    <script type="text/babel" src="js/layout.js"></script>
</body> 
</html>

layout.js

import React from "react";
import ReactDOM from "react-dom";

import Header from "./header";

class Layout extends React.Component {
    render() {
       return(
        <div>
           <Header/>
        </div>
    );
    }
}

const app = document.getElementById("app");
ReactDOM.render(<Layout/>, app);

和header.js

import React from "react";
import ReactDOM from "react-dom";

export default class Header extends React.Component {
    render() {
        return(
            <h1>Hello header</h1>
    );
    }
}

1 个答案:

答案 0 :(得分:3)

Babel仅处理转换部分(即将es2015和jsx语法转换为有效的ES5)。但您仍然需要使用bundler(webpack,browserify)或模块加载器(systemjs或jspm)来加载模块。

以下是使用SystemJS的示例。 Example

配置systemjs loader以从cdn

加载库
System.config({
    transpiler: 'babel',
    baseURL: '',
    map: {
      babel: 'https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js',
      react: 'https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js',
      'react-dom': 'https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js'
    }
});

// load application
System.import('script.js');

导入本地文件

// inside script.js
import React from "react";
import ReactDOM from "react-dom";
import Header from "./header.js"; //note extension

class Layout extends React.Component {