首页 > 解决方案 > 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 文件中的脚本标记中。

标签: javascripthtmlreactjs

解决方案


您需要告诉节点您要使用ESmoduleimportexport关键字等功能。

为此,将此行添加到您的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 导入


推荐阅读