2

I am trying to import one function declared in a javascript file into another javascript file, but can't get it right. I am not using any transpiler.

I am trying to import variables and functions from one JavaScript file to another but don't want to use Transpilers. I can't get it right how to import and export functions. I am using Adobe{Brackets} as my IDE.

I have already converted the importing script to a module, but still I am unable to export or import. As a second try, I tried converting exporting script to a module but still get the following error:

Parsing Error- Export and import keyword are reserved.

As a third try, I converted both files to a module. Still it does not work.

HTML:

<html>
<head><title>Test1</title>
</head>
<body>
<button type = "button" class= "slctbtn" onclick= "select()" id= "selct_btn">Select</button>
</body>
<script src="javascript/select.js"></script>
<script type="module" src="javascript/Test.js"></script>
</html>

javascript/Test.js:

var today = 28;
export {today};

javascript/select.js:

import {today} from "./javascript/Test.js";
function select(){
    var month = "august";
    var year = "2019";
    alert("this is " + month + " of the year " + year + " and today is " + today + " day.");
}

Expected Result: Alert must show text like this image

4

3 Answers 3

1

You can't really mix and match module and non-module JS. So:

  • Use only one <script> element
    • Make it type="module"
    • Load select.js with it
  • Use import {today} from "./Test.js"; because the path is relative to the JS
  • Since variables in modules are not global, use addEventListener inside select.js and not an onclick attribute.
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

import {today} from "./Test.js";

Comments

0

Replace import {today} from "./javascript/Test.js";

with import {today} from "./Test";;

Here is working demo https://stackblitz.com/fork/react?file=index.js

1 Comment

That will be necessary to get the code working, but it isn't the source of the error: trying to import in a regular js script is. Needs type="module".

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.