我正在向我现有的 html 页面添加反应。按照此处的说明在此处输入链接描述。然后这工作得很好,直到我导入不同的组件。
我的 html 代码:
<!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.0">
<title>Test2</title>
</head>
<body>
<h1>Hello World</h1>
<div id="like_button_container"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin>.
</script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"
crossorigin></script>
<!-- Load our React component. -->
<script src="like_button.js"></script>
</body>
</html>
我的 like_button.js 代码:
'use strict';
import Another from "./another.js"; //problem here, if you comment this line, it works.
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);
和我的 another.js 代码:
'use strict';
const e = React.createElement;
class Another extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this (another).';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
export default Another;
谢谢您的回答。
编辑:我在 package.json 文件中添加了“type”:“module”。最新情况如下;
{
"name": "test2",
"version": "1.0.0",
"description": "",
"main": "another.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module"
}
但它仍然不起作用,我在控制台中收到相同的错误。
编辑2:解决问题。仅将 ("type": "module") 添加到 package.json 是不够的,我还必须将 (type="module") 添加到 html 文件的脚本标记中。
你需要告诉节点要使用的ESmodule
功能,如import
和export
关键字。
为此,将此行添加到您的package.json
文件中。
"type": "module"
package.json
指定类型的示例文件。
{
"name": "pup",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module"
}
您还需要添加type="module"
到以index.html
.
<script src="like_button.js" type="module"></script>
这将停止您收到的错误。
也值得一看commonjs 与 es6 导入
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句