I'm developing a express application and Im trying to do the below thing and I keep getting the same error over and over - "GET http://localhost:3000/javascript/module2 net::ERR_ABORTED 404 (Not Found)"
Could someone please point out to me what mistake I am committing and point me in the right direction? Below is my code -
Module1.js
import theFunc from "./module2";
console.log("In module 1");
theFunc();
Module2.js
export default function theFunc() {
console.log("from module 2");
}
index.html
<html>
<body>
Should show the result in console.
<script type="module" src="./javascript/module1.js"></script>
</body>
</html>
Thanks a ton in advance! :)
The message points out the issue, but it's still pretty easy to miss.
GET http://localhost:3000/javascript/module2 net::ERR_ABORTED 404
is the issue, because instead of
http://localhost:3000/javascript/module2
the URL is actually
http://localhost:3000/javascript/module2.js
with a .js extension.
The issue is that
import theFunc from "./module2";
should be
import theFunc from "./module2.js";
The import and export statements belong to ES6 therfore you need to use a transpiler like Babel.
You second option is to use require which the equivalent in ES5:
First add this script to the head of your html:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
</head>
<body>
Change these lines:
import theFunc from "./module2";
becomes
var theFunc = require("./module2");
& this one too:
export default function theFunc() {
console.log("from module 2");
}
becomes:
function theFunc() {
console.log("from module 2");
}
module.exports = theFunc;
Related
I'm trying to add an import to one of my JS files (both JS are in the same directory) but it seems to break with the following error:
"SyntaxError: import declarations may only appear at top level of a module"
<--HTML-->
click me
<---main_file.js--->
import { new_func } from "./new_file.js";
function run_my_func(){
...
}
<---new_file.js--->
export { new_func };
function new_func(){
....
}
I tried to read other questions on this topic but couldn't find a proper solution.
I've tried also changing the ahref to script type="module" but it didn't work either.
any suggestions?
EDIT:
So I managed to fix it, and it might not be the best practice but it works for my scenario as I want to use a specific function is several JS files -
in the HTML script that loads the function I want to export (new_file.js) I added type="module".
<script type="module" src="js/new_file.js"></script>
made new_func a global variable by adding it to window:
window.new_func = function() {
...
}
now I used new_func normally in every JS file that was imported after new_file
I seem to be going in circles trying to get a simple nested .js files to work. I start with these 2 files and it works as expected:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="module" src="./scripts/file1.js"></script>
<title>Hello World Page</title>
</head>
<body >
<div>
Some prompt: <input id="Xxx" onkeyup="file1Go('index.html calling file1Go()')"/><br />
</div>
</body>
</html>
file1.js
function file1Go(msg) {
alert('In file1.js - ' + msg);
}
Then I create a new file2.js and modify file1.js to import it. I also modify it to export the function that is used. I then also modify the index.html file's script tag to tell it that file1.js is now a module like this (to avoid the 'Cannot use import outside of a module' error):
<script type="module" src="./scripts/file1.js"></script>
Modified file1.js
import { file2Go } from "./file2.js"
export function file1Go(msg) {
alert('In file1.js - ' + msg);
file2Go(msg);
}
New file2.js
export function file2Go(msg) {
alert('In file2.js - ' + msg);
}
This results in the html page loading and both .js files downloading without error, but at runtime it fails to find the exported function in file1.js:
(index):11 Uncaught ReferenceError: file1Go is not defined at HTMLInputElement.onkeyup ((index):11)
That's it. What stupid thing am I doing wrong or what am I missing?
And thanks in advance for taking the time.
Afterthought: Putting similar .js files in a folder and executing with node.js appears to work.
More Info:
I've discovered that the following <script> tag does import and execute the function. I can also set HTML event handlers there. It's just that functions are apparently not visible outside of the scope of the <script> tag which to my little brain appears to be unduly restrictive and unuseful.
<script type="module">
import { file1Go } from "./scripts/file1.js";
file1Go("logging on start in <head> tag..."); // works
document.getElementById('Xxx').onkeyup = file1Go; // also works
</script>
Note: My endgame here is to use TypeScript which would have many files. I removed TypeScript from my repro for simplicity and to target the root cause of my issue. Once I understand the scoping issue I'll move on to TypeScript.
I'm trying to understand how to use modules in javascript.
But it seems that if I import a module, then I cannot log anything to console.
Here's my code:
index.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="js/scene.js" type="module"></script>
<script src="js/main.js" type="module"></script>
</body>
</html>
scene.js:
class Scene {
constructor() {
console.log("Scene created");
}
}
export default Scene;
main.js:
import { Scene } from './js/scene.js';
var scene = new Scene();
console.log("Hello World");
The Expected Result:
Scene created
Hello World
The Result I Get:
Nothing (No Result)
What is wrong with my code and how can I properly use a module?
I see 3 mistakes
in index.html the first script tag is useless.
import is relative to script file, not html.
Scene.js export a default value not a variable named Scene.
solutions:
import Scene from './scene.js';
or
remove default in Scene.js, and import {Scene} from './scene.js';
In your scenario, I believe that line 1 of main.js is throwing an error. In your index.html file, you're suggesting that you have a folder named js with both javascript modules in it; however, in the main.js file, you're suggesting that scene.js is at path js/js/scene.js.
You probably meant import { Scene } from './scene.js';.
You should open your browser's console to view any errors.
For example, if you are using Google Chrome, becoming familiar with the Chrome Devtools will be invaluable in allowing you to resolve bugs like this one by yourself in the future.
The Chrome Devtools console will allow you to view errors in your website, which will give you an immediate answer on what is wrong. In addition, setting breakpoints will allow you to step-through each line of code and trace the flow of executed lines of code and the value of variables at each point in time.
Learn more here: https://developers.google.com/web/tools/chrome-devtools/javascript
I'm writing JavaScript for the browser, my script.js has something like
import { foo, bar } from "./lib/sth.js"
function main() { ... }
Then I have this in my browser:
<script type=module src="./script.js"></script>
<body onload="main();"> ... </body>
But it's keep giving me this error:
Uncaught ReferenceError: main is not defined
at onload ((index):7)
Why is my main now defined? It works fine before I use type=module, but with the import statement, I believe it has to be type=module
Thanks for #HereticMonkey and #FelixKling!
window.onload = function() { ... }
does work for my problem. Yet I'm confused why import is designed like this. Suppose I just wanna use some library in my script so I import it, why this makes my script has to be a module as well?
I can't figure this out. I have a small app setup with an index.html that includes a javascript file. On the same directory as that file is another file named myJsModule.js with the following code:
export default class{
doStuff()
{
console.log("calling goStuff() from external Module");
}
}
The main javascript file that is loaded from the html then does the import in this way:
import myJsModule from "myJsModule";
// TESTING MODULES
let myNewModule = new myJsModule();
myNewModule.doStuff();
I have a local web server running using Node, so I'm accesing this index.hmtl through my localhost: http://127.0.0.1:8080.
Im getting the following error: Uncaught SyntaxError: Unexpected identifier (referring to myJsModule on my main js file). I also tried using babel to transpile this into previous javascript. I had the same problem using the "require".
Shouldn't my local server figure this out? Or am I using this wrong?
As of Chrome 61, modules are natively supported. I was able to get your example working with the following HTML and JavaScript.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Native Module</title>
</head>
<body>
<p>Hello, world!</p>
<script type="module">
import MyJsModule from './MyJsModule.js';
let myJsModule = new MyJsModule();
myJsModule.doStuff();
</script>
</body>
</html>
MyJsModule.js:
export default class MyJsModule {
doStuff() {
console.log("calling doStuff() from external Module");
}
}