[英]Syntax Error: Cannot use import statement outside a module / Unexpected token '<' - related errors
I keep getting this error:我不断收到此错误:
SyntaxError: Unexpected token '<'
at Loader.moduleStrategy (internal/modules/esm/translators.js:81:18)
at async link (internal/modules/esm/module_job.js:37:21)
I've read many posts with this or similar errors, but they don't seem to be related/helpful.我已经阅读了许多包含此错误或类似错误的帖子,但它们似乎没有相关/有帮助。
here is one example:这是一个例子:
...
const posts = usePosts()
function App() {
return (
<div>
{posts &&
posts.map(post => {
<div>{post.title}</div>
})
}
<ReactQueryDevtools/>
</div>
)
}
ReactDOM.render(<App />, document.getElementById("root"));
the error happens at the very first <错误发生在第一个 <
adding "type": "module" at the top of package.json like this doesn't change it:在 package.json 顶部添加 "type": "module" 不会改变它:
{
"name": "my-app",
"version": "0.0.0",
"type": "module",
"devDependencies": {
...
(note, that I've tried that example in Webstorm and VSCode; the one below just in Webstorm) (请注意,我已经在 Webstorm 和 VSCode 中尝试过该示例;下面的示例仅在 Webstorm 中)
here is another example:这是另一个例子:
import * as React from 'react'
import ReactDOM from 'react-dom'
import {Logo} from './components/logo'
function App() {
return (
<div>
<Logo width="80" height="80" />
<h1>Bookshelf</h1>
<div>
<button onClick={() => alert('login clicked')}>Login</button>
</div>
<div>
<button onClick={() => alert('register clicked')}>Register</button>
</div>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
what is interesting about this one: it works, as long as I start the project with the provided start script.这个有趣的是:只要我使用提供的启动脚本启动项目,它就可以工作。
node filename.js returns:节点文件名.js 返回:
(Use `node --trace-warnings ...` to show where the warning was created)
/Users/johannes/Documents/GitHub/bookshelf/src/index.final.js:1
import * as React from 'react'
^^^^^^
SyntaxError: Cannot use import statement outside a module
and when I add "type": "module to package.json it returns the same unexpected token error as above.当我向 package.json 添加 "type": "module 时,它返回与上述相同的意外令牌错误。
I'm using: Node v14.2.0 ESLint: 7.16.0我正在使用:节点 v14.2.0 ESLint:7.16.0
What am I missing?我错过了什么?
Few things to note有几点需要注意
import
and arrow functions ( () => {}
) are what we call the ES6 syntax.import
和箭头函数 ( () => {}
) 这样的关键字就是我们所说的 ES6 语法。 So if you are working with them you probably need a transpiler like Babel (You can find so many tutorials on this topic)JSX
(Read here ) and once again if you use them you need Babel to transpile that syntax to plain JS.JSX
(请阅读此处),如果您使用它们,您需要Babel将该语法转换为纯 JS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.