我有 php 页面并将 React 导入为 s 文件
<div id="app"></div>
<script src="/assets/app.js"></script>
在 app.js 文件中
const container = document.getElementById('app');
const root = ReactDOM.createRoot(container);
root.render(<MyApp/>);
app.js 使用 jsx,所以我通过控制台命令渲染它
npx babel ./views/post/app.js -d --out-file ./web/assets/app.js --plugins=@babel/plugin-transform-react-jsx
一切正常,但 app.js 变得更大。因为我写了很多组件,所以我决定将其放在模块上 我制作了 SeoKeywords.js 文件
export default function SeoKeywords() {
return (......)
}
现在我尝试按照这里所说的那样导入它https://react.dev/learn/importing-and-exporting-components
我添加了从'./SeoKeywords'导入SeoKeywords;在 app.js 之上 现在在资产文件夹中我有 app.js 广告 SeoKeywords.js
加载页面时出现错误 未捕获的语法错误:无法在模块外部使用 import 语句(位于 app.js:1:1)
要在脚本中使用导入语法,您需要将其类型指定为模块,即:
<script type="module" src="/assets/app.js"></script>
MDN 页面对模块是什么以及它们如何工作有很好的介绍,请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#a_background_on_modules