javascript - reactjs中的“未捕获的语法错误:无法在模块外使用导入语句”错误
问题描述
我正在向我现有的 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);
和我的另一个.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 文件中添加了“类型”:“模块”。最新情况如下;
{
"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:解决问题。仅在 package.json 中添加 ("type": "module") 是不够的,我还必须将 (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 vs es6 导入
推荐阅读
- python - 如何让这个脚本检查目录中的每个文件但不记录每个单独的检查?
- java - 如何通过 css 更改 JavaFX ComboBox 的箭头按钮中的背景颜色?
- c# - 如何将两个不同的控件动态绑定到单个数据网格单元中的两个不同的数据源
- events - AEM 6.3 设置 PageEvent 处理程序/侦听器
- android - 没有活动的 Airbnb-DeepLinkDispatch
- c# - 如何修复“EntryPointNotFoundException”
- vim - 在vim中沿左边距创建一个4-5个字符的列
- asp.net - Asp.Net 注释导致 VS Code 语法高亮停止工作
- r - 使用 R 中的函数迭代包含不同长度的列号列表的数据框
- c# - MongoDB 查询到 C# 等效的 ObjectID 子集