[英]Uncaught SyntaxError: Cannot use import statement outside a module using reactjs CDN Links
I am writing an app in Reactjs using react CDN Links, not 'npx create-react-app'.我正在使用 React CDN 链接而不是“npx create-react-app”在 Reactjs 中编写一个应用程序。 I have created an index.html, index.js, and App.js files.
我创建了 index.html、index.js 和 App.js 文件。 I want to import the App.js component in Index.js file using
import App from '../components/App.js'
but it is giving "can not use import statement outside module" error on the browser (client-side).我想使用
import App from '../components/App.js'
在 Index.js 文件中导入 App.js 组件,但它在浏览器(客户端)上给出“不能在模块外使用导入语句”错误. following are the codes以下是代码
INDEX.HTML索引.HTML
<!DOCTYPE html>
<html>
<head>
<title>Notepad Web App</title>
</head>
<body>
<div id="root"></div>
<!-- React CDN -->
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<!-- JSX -->
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<!-- External JS File -->
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
INDEX.JS索引.JS
import App from '../components/App.js'
const e = React.createElemnt;
ReactDOM.render(e(App), document.querySelector('#root'));
APP.JS APP.JS
const e = React.createElement;
function App()
{
return(
e("h1",{},'This is React App')
)
}
export default App;
To include a JavaScript module in an HTML page, you have to tell that to the browser explicitly by adding type="module"
:要在 HTML 页面中包含 JavaScript 模块,您必须通过添加
type="module"
明确告诉浏览器:
<script type="text/javascript" type="module" src="./index.js"></script>
You can read more about modules and how to use them here .您可以在此处阅读有关模块以及如何使用它们的更多信息。
EDIT:编辑:
Regarding the new error you get, see here :关于您收到的新错误,请参见此处:
Unlike regular scripts, ES6 modules are subject to same-origin policy .
与常规脚本不同,ES6 模块受制于同源策略。 This means that you cannot
import
them from the file system or cross-origin without a CORS header (which cannot be set for local files).这意味着如果没有 CORS header (无法为本地文件设置),则无法从文件系统或跨域
import
它们。
Basically you need to run this code from a (local) server.
基本上,您需要从(本地)服务器运行此代码。
You can use live-server :您可以使用live-server :
npm install -g live-server
live-server
Changing the type to "module"
can solve the issue like this:将类型更改为
"module"
可以解决如下问题:
<script type="module" src="./index.js"></script>
Also, you have a syntax error line 2
in index.js const e = React.createElemnt;
此外,您在 index.js
const e = React.createElemnt;
中有一个语法错误line 2
。 you have a missing e
in the word Elemnt
.您在
Elemnt
一词中缺少e
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.