Reputation: 43
So I am trying to learn modules from a youtube video and I'm following along with him but for some reason my code is the exact same as his and is giving me the error
SyntaxError: Cannot use import statement outside a module
I'm not sure if its because my directories are wrong? I have it under This PC > Desktop > Javascript > module > js > main.js This is the code from main.js
import{double} from './utils.js'
console.log(double(5))
I also have a index.html file located in the module folder This is my index.html code.
<!DOCTYPE html>
<head>
<title>JavaScript Modules</title>
<meta name="viewport" content="width=device-width, initial scale=1.0">
<meta charset="utf-8">
<link rel="stylesheet" href="/assets/dcode.css">
<link rel="shortcut icon" href="/assets/favicon.ico" type="image/x-icon">
</head>
<body>
<h1>JavaScript Modules</h1>
<u1>
<li>Split up your code into separate components</li>
<li>Therefore easier to maintain and organize</li>
<li>Supported in major browsers(excl. IE)</li>
</u1>
<script type="module" src="./js/main.js"></script>
</body>
I'm trying to import
code from my utils.js file which is in the same folder as main.js
This is my utils.js code.
export function double(n){
return n * 2;
}
When I run the code on the main.js file is where I'm getting the error:
SyntaxError: Cannot use import statement outside a module
Upvotes: 3
Views: 1900
Reputation: 1291
You need to run your own webserver. An easy one is to get the Web Server for Chrome. You just run it, point it to your local computer folder, and it will give you a localhost port number where your computer is serving the folder. That way you can access your local folders over HTTP.
With the following folder structure:
/exports/
user.html
importer.js
exporter.js
Where user.html
is the page using the importer.js
script, which in turn loads exporter.js
, you use the following syntax:
user.html
-- the type="module"
notation is necessary.
<script src="importer.js" type="module"></script>
importer.js
-- the ./
relative notation is obligatory.
import { doStuff } from './exporter.js'
doStuff()
exporter.js -- in a production environment, this is your library or module.
function doStuff() {
console.log('Do stuff')
}
export { doStuff }
With a local server, the above setup will log Do stuff
in the console.
Forgetting type="module"
results in an Uncaught SyntaxError: Cannot use import statement outside a module
, not having a relative URL will result in an Uncaught TypeError: Failed to resolve module specifier "exporter.js". Relative references must start with either "/", "./", or "../"
, and having the wrong URL results in a 404.
Upvotes: 2