admin管理员组

文章数量:1394585

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?

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?

Share Improve this question asked Mar 12, 2021 at 16:52 חיים חדדחיים חדד 5221 gold badge5 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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>

Sometimes you need to update the JS version of the file after you added the type="module" as below:

<script type="module" src="~/js/site.js?v=101" asp-append-version="true"></script>

Because your browser can cache already existing scripts.

本文标签: javascriptHow to import a js file module in ASPNET CORE MVCStack Overflow