我正在尝试使用RequireJS babel plugin和ReactJS在es6中创建一个简单的类,但无法弄清楚如何Import或者需要来自RequireJS的Reacts库还导出要在另一个脚本中使用的类。
下面是我到目前为止所做的jsbin,但是当我到达es6类时出现错误,因为导出在require调用内,但是如果我删除了require调用React.Component就不存在了。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.2/require.min.js"></script>
<script src="https://output.jsbin.com/guvalasowi.js"></script>
<title>JS Bin</title>
</head>
<body>
<div id="a-div"></div>
</body>
</html>
require({
paths: {
es6: "https://cdn.rawgit.com/mikach/requirejs-babel/master/es6",
babel: "https://cdn.rawgit.com/mikach/requirejs-babel/master/babel-5.8.34.min",
react: "https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-with-addons.min",
reactDOM: "https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.min",
test: "https://output.jsbin.com/sahudexegu"
}
});
require(['es6!test', 'reactDOM'], function(test, ReactDOM){
ReactDOM.render(
table,
document.getElementById("a-div")
);
});
require(['react'], function(React){
class Welcome extends React.Component {
render() {
return <h1>Hello</h1>;
}
};
export {Welcome};
});
tl; dr:在es6脚本中如何从requirejs中获取模块并仍然导出类对象?
答案 0 :(得分:0)
首先,要回答您的主要问题,导出可以这样做:
requirejs.config({
paths: {
'es6': "bower_components/requirejs-babel/es6",
'babel': "babel-5.8.34.min",
'react': 'https://unpkg.com/react@15.3.2/dist/react',
'react-dom': 'https://unpkg.com/react-dom@15.3.2/dist/react-dom',
'test': "test"
}
});
requirejs(['es6!test', 'react', 'react-dom'], function(test, React, ReactDOM) {
var Welcome = test.default;
ReactDOM.render(
<Welcome />,
document.getElementById("a-div")
);
});
组件的使用(你的ReactDOM有问题包括原样):
{{1}}
答案 1 :(得分:0)
下面的工作示例,我必须从接受的答案中改变一件事是在requirejs配置脚本中使用jsx。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.2/require.min.js"></script>
<script src="https://output.jsbin.com/zeyajapoxa.js"></script>
<title>JS Bin</title>
</head>
<body>
<div id="a-div"></div>
</body>
</html>
require({
paths: {
es6: "https://cdn.rawgit.com/mikach/requirejs-babel/master/es6",
babel: "https://cdn.rawgit.com/mikach/requirejs-babel/master/babel-5.8.34.min",
react: "https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-with-addons",
'react-dom': "https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom",
test: "https://output.jsbin.com/poremuqupu"
}
});
requirejs(['es6!test', 'react', 'react-dom'], function(test, React, ReactDOM) {
console.log(arguments)
//var Welcome = test.default;
console.log(test)
ReactDOM.render(
React.createElement(test, test),
document.getElementById("a-div")
);
});
import React from 'react';
class Welcome extends React.Component {
render() {
return <h1>Hello</h1>;
}
};
export default Welcome