javascript - 如何使用 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);
谢谢你。
解决方案
请注意在您链接的页面中如何没有对import
s 或export
s 的引用。
还有那个页面是如何说的:
提示
我们在这里使用 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
推荐阅读
- html - 如何使引导图标位于按钮的中心?
- youtube-api - 即使实际上没有超出 YouTube 数据 API 配额
- node.js - 处理 HTTPS 的最佳实践是什么?
- laravel - 在 api 中使用 sanctum 时策略不正确
- tensorflow - Session.close() 方法是否会中断另一个线程中 TensorFlow 中 Session.run() 调用的当前正在执行的运行?
- c# - 如何在 Unity 测试脚本中触发 OnMouseOver/OnMouseExit?
- javascript - 如何向该网站添加浏览器/会话历史记录?
- swift - 在 MacOS 下使用 systemimage 在运行时设置 NSImage.image
- javascript - 为什么 Express.js res.send(jsonObject.property) 会使应用程序崩溃?
- php - 使用 PHP 获取元素