首页 > 解决方案 > 如何使用 JSX 导入模块?

问题描述

我是 React 的新手。我已使用此站点上的信息将其添加到项目中:

https://reactjs.org/docs/add-react-to-a-website.html

Run npm init -y (if it fails, here’s a fix)

Run npm install babel-cli@6 babel-preset-react-app@3

然后,

npx babel --watch src --out-dir . --presets react-app/prod

每当我尝试添加一个模块时,它都会给我:

未捕获的语法错误:无法在模块外使用 import 语句。

这是我导入的方式:

import { PostcodeLookup } from "@ideal-postcodes/postcode-lookup" 

(我已经在我的 react js 文件的顶部和一个在 componentDidMount() 方法中调用的单独脚本文件中尝试了这个,方法是:

 const script = document.createElement("script");

script.src = "my_script.js";
script.async = true;

document.body.appendChild(script);

谢谢你。

标签: javascriptreactjsjsx

解决方案


请注意在您链接的页面中如何没有对imports 或exports 的引用。
还有那个页面是如何说的:

提示
我们在这里使用 npm 只是为了安装 JSX 预处理器;

这意味着它只会将 JSX 表达式处理为React.createElement函数调用。如果你想使用模块,你要么需要通过改变type你的<script来使用本机模块module

<script type="module" src="./main.js">

或使用捆绑器。

要使用捆绑器,请查看 React 教程的下一页: https ://reactjs.org/docs/create-a-new-react-app.html


推荐阅读