I am trying to use the import keyword in a .jsx file in my ASP.NET MVC 5 project. I want to be able to import other React components into another React component, however, when using the import keyword, I am getting the following error:
Uncaught SyntaxError: Cannot use import statement outside a module
Below is my code:
Index.cshtml:
@{
Layout = null;
}
<html>
<head>
<title>Hello React</title>
</head>
<body>
<div id="content"></div>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.development.js"></script>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>
<script src="@Url.Content("~/Scripts/Tutorial.jsx")"></script>
</body>
</html>
Tutorial.jsx:
import Comment from '../Scripts/Comment.jsx';
class Tutorial extends React.Component {
render() {
return (
<div className="commentBox">
<h1>Homepage</h1>
<Comment />
</div>
);
}
}
ReactDOM.render(<Comment />, document.getElementById('content'));
Comment.jsx:
class Comment extends React.Component {
render() {
return (
<p>I am a comment!</p>
);
}
}
export default Comment;
If I do not have the imports or if I add the Comment class directly inside of the Tutorial.jsx, it runs fine, but that is not what I am looking for. I want to be able to have all my components in separate .jsx files and be able to import certain components into different ones. Ideas?
EDIT: Fixed export default Comment, however error is still appearing
The error "Cannot use import statement outside a module" results when a <script> element contains an import statement but the <script> element itself is not declared as an ECMAScript (or ES) module.
The import statement requires your script file Tutorial.jsx to be declared a module. Add the type attribute with the value module to the <script> tag.
See the first paragraph at the top of the page https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
The import statement cannot be used in embedded scripts unless such script has a type="module".
In your HTML page, change:
<script src="@Url.Content("~/Scripts/Tutorial.jsx")"></script>
to
<script type="module" src="@Url.Content("~/Scripts/Tutorial.jsx")"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With