4

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?

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.