简体   繁体   English

浏览器中的javascript无法同时识别“导入”和JSX

[英]In-browser javascript won't recognize “import” and JSX at the same time

I'm trying to create a simple React app that imports components from a components directory. 我正在尝试创建一个简单的React应用程序,该应用程序从components目录中导入组件。 Currently this is my folder structure: 当前,这是我的文件夹结构:

main
|_components
|   |_FirstComponent.js
|_index.html

FirstComponent.js FirstComponent.js

export class FirstComponent extends React.Component{
    render(){
        return (
            <h1>Hello World</h1>
        )
    }
}

In index.html, I have scripts loading react, react-dom, and babel. 在index.html中,我有脚本加载react,react-dom和babel。 Here is my JS code so far: 到目前为止,这是我的JS代码:

<script type="module">
    import FirstComponent from "./components/FirstComponent.js";
</script>

Which gives me the error: Uncaught SyntaxError: Unexpected token '<' 这给了我错误: Uncaught SyntaxError: Unexpected token '<'

That's an error with JSX parsing, but when I switch the script type to text/babel : JSX解析是一个错误,但是当我将脚本类型切换为text/babel

<script type="text/babel">
    import FirstComponent from "./components/FirstComponent.js";
</script>

I get this error: Inline Babel script:2 Uncaught ReferenceError: require is not defined 我收到此错误: Inline Babel script:2 Uncaught ReferenceError: require is not defined

In other words, if type is module, the browser can't read JSX, but if the type is babel, the browser doesn't recognize require, aka import. 换句话说,如果类型是模块,则浏览器无法读取JSX,但是如果类型是babel,则浏览器将无法识别要求,也就是导入。

How do I get the browser to properly load the component? 如何使浏览器正确加载组件?

As a workaround, you can import your FirstComponent to your index.html page by simply doing this: 解决方法是,只需执行以下操作即可将FirstComponent导入到index.html页面:

<script type="text/babel" src="./components/FirstComponent.js"></script>

And in FirstComponent.js, remove the import and export statements so that file only has the FirstComponent class/functional component . 在FirstComponent.js中, 删除import和export语句,以便文件仅具有FirstComponent类/功能组件 This will load the class as inline babel script and your component would be available to use. 这会将类作为嵌入式babel脚本加载,您的组件将可以使用。 You can use ReactDOM.render() at the bottom of the index.html to render the component. 您可以使用index.html底部的ReactDOM.render()渲染组件。 This is an easy workaround. 这是一个简单的解决方法。

FirstComponent.js FirstComponent.js

// No import statements
class FirstComponent extends React.Component{
    render(){
        return (
            <h1>Hello World</h1>
        )
    }
}
// No export default statement

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM