Reputation: 67
I have set up a html page that contains a button that when clicked, activates a function from an external javascript file. The JS file in question imports two other functions from another JS file. However when I load the html file in my browser (Safari 12.0.2) and look at it in the debugger, I get an error stating "SyntaxError: Unexpected token '{'. import call expects exactly one argument."
The files are named "html_test_run.html", "test_run_javascript.js" and "export_test_run.js". I have tried setting the type of the script to "module" but that only resulted in a new error that said "Origin null is not allowed by Access-Control-Allow-Origin". I have also attempted to have three html tags, the first two had the source of the js files and the third defined a new function that the button would use instead, that didn't work either.
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Test run</title>
<meta name="description" content="Test run">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--
<link rel="stylesheet" href="">
-->
<script type="text/javascript" src="assets/test_run_javascript.js">
</script>
</head>
<body>
<button type="button" name="button" onclick="doSomething()">Click me</button>
</body>
</html>
First JS file:
import {doSomethingElse1, doSomethingElse2} from "export_test_run.js";
function doSomething(){
doSomethingElse1();
doSomethingElse2();
console.log("Test successful");
}
Second JS file:
function doSomethingElse1(){
console.log("Test successful1");
}
function doSomethingElse2(){
console.log("Test successful2");
}
export {doSomethingElse1, doSomethingElse2};
I expected the files would load correctly and the button would call the function "doSomething()" when clicked.
Any help would be greatly appreciated.
Upvotes: 5
Views: 9259
Reputation: 61
You have to correctly include a script on your page showing that the script type is "module":
<script src="/js/index.js" type="module"></script>
In case if the browser doesn't support modules you can simply process that using "nomodule" attribute:
<script nomodule>
console.info(`Your browser doesn't support native JavaScript modules.`);
</script>
Upvotes: 5
Reputation: 316
You can include the two of your js files in the first page:
<script type="text/javascript" src="export_test_run.js">
</script>
<script type="text/javascript" src="assets/test_run_javascript.js">
</script>
Remove the export and import code from your js files! Use the correct paths for the including.
Upvotes: 0