Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a js file module in ASP.NET CORE MVC?

I just created a js module file on wwwroot/js/base.js:

export const elements = {
...somthing
};

When I try to import it from wwwroot/js/site.js, such as

import {elements} from './base';

I geth this error:

Uncaught SyntaxError: Cannot use import statement outside a module

What am I missing?

like image 612
חיים חדד Avatar asked Sep 02 '25 05:09

חיים חדד


1 Answers

If you want to import a js file module,you need to add like this(You must use type="module" in script tag):

<script type="module" src="~/js/site.js"></script>

site.js is imported in Views/Shared/_Layout.cshtml by default.You can check Views/Shared/_Layout.cshtml and change

<script src="~/js/site.js" asp-append-version="true"></script>

to

<script type="module" src="~/js/site.js" asp-append-version="true"></script>
like image 196
Yiyi You Avatar answered Sep 04 '25 18:09

Yiyi You