Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript module not working in browser?

Alright, I have looked on this site and have found several different answers, none of which have worked for me. Basically had a js file that had many functions in it along with the main code for the app. I wanted to move all my functions to another js file so that I could clean up my code a little. I am fairly new to js but I know in python it was as simple as saying "import (module) as (nickname) from (path)"

anyways let's say I have a function named show message in my functions.js module.

export function show_message(){     alert("Hello"); } 

and then I at the top of my main.js file I did

import { show_message } from './functions.js' //I have also tried to import like this: import * as func from './functions.js'  //And then I call it show_message(); //I have also tried func.show_message(); 

I know this is something simple, but as I said everywhere I have looked I have seen different answers, none of which work for me. I am using Firefox btw. I am also getting an error in the console saying that my import declarations need to be at the top of my module, I fixed that by specifying the type in my HTML link (script src="/static/main.js" type="module") The error went away but is now saying "same origin policy disallows reading the remote resource at the file (path) (reason: cors request not HTTP)."

And the other error says "module source URI is not allowed in this document".

which makes me think maybe my syntax for importing is right and the error is in my HTML code?

Any help is appreciated.

like image 546
RobotMan Avatar asked Sep 02 '18 18:09

RobotMan


People also ask

Why is my JavaScript not running?

On the web browser menu click on the "Edit" and select "Preferences". In the "Preferences" window select the "Security" tab. In the "Security" tab section "Web content" mark the "Enable JavaScript" checkbox.

Do browsers support ES6 modules?

Safari, Chrome, Firefox and Edge all support the ES6 Modules import syntax.

Why JS file is not working in HTML?

You should put all javascript code in a <script> tag for the browser to recognize and make it run and for the src attribute of the script tag to find your 'script. js' file, it just has to be in the same directory as the html file, you don't need to specify the entire file root.


2 Answers

0. The short answer

You need to install and run a local web server. - For a suggestion on how, read on.

1. The basics

I tried a simple HTML file – index.html – as follows:

<!-- index.html - minimal HTML to keep it simple --> <html> <head>   <meta charset="UTF-8">   <link rel="shortcut icon" href="#"> </head> <body>   <h1>Hello world!</h1>   <p>Experimenting with JavaScript modules.</p>   <script type="module" src="js/functions.js"></script> </body> </html> 

In the subfolder js I put the JavaScript file functions.js:

// js/functions.js alert('Hello'); 

When double-clicking index.html, my default web browser – Firefox 89.0 (64-bit) – shows the following, after pressing F12. Notice how the JavaScript code is not running:

JavaScript not working in browser.

The error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/stackexchange/reproduce/jsModule/moduleNW/basics/js/functions.js. (Reason: CORS request not http).

A cheating "solution" is to (temporarily) remove type="module" from the HTML code.
The alert then displays without errors.

But I want to run the JavaScript code as a module, so I put back type="module" in the HTML.

2. Install and run a local web server

To run it as a module, it needs to run on a web server. Thus, if you want to run the code on your own computer, you will need to (install and) start a local web server.
One currently popular alternative is live-server. Here is what worked for me.

  • Open a terminal. (On Windows: cmd.exe.)
  • Type npm and hit Enter to see if Node.js is installed.
  • If you get command not found, download at https://nodejs.org/en/download/ and install. 1
    (On Ubuntu, you can try sudo apt install -y nodejs.)
  • Install live-server: npm install live-server -g.
  • Change directory to where your page lives: cd <path-to-index.html>.
  • Start the server: live-server .
    (Should open localhost:8080 in your default browser and show the alert. See below.)

JavaScript running locally on live-server.

Note 1. I am on Windows 10, but the above instructions should work fine on Linux and macOS too.
Note 2. Here I used Firefox 89.0, but I have tried Google Chrome 91.0 as well. The only notable difference is the CORS error message, which in Chrome reads:
Access to script at 'file:///C:/stackexchange/reproduce/jsModule/basics/js/functions.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

3. Exporting and importing

Next I create a new folder demo2 containing the following demo2.html:

<!-- demo2.html - even shorter HTML for simplicity --> <body>   <h1>Hello world!</h1>   <p>Javascript modules.</p>   <script type="module" src="js/main.js"></script> </body> 

I also create the following three JavaScript files in the subfolder js:

// js/module1.js export function hi () { console.log('Hi from module 1.'); } 

and

// js/module2.js export function howdy () { console.log('Howdy from module 2!'); } 

and

// js/main.js import { hi } from './module1.js'; import { howdy } from './module2.js'; hi(); howdy(); 

Now I run live-server from the terminal in the folder where demo2.html resides. This time I start by typing live-server --port=1234 --entry-file=demo2.html and hitting Enter. Screenshot:

JavaScript running when called from several sub-modules.

References:

  • Installing Node.js live-server
  • The live-server docs
  • Live-server can't find the file specified
  • Export and Import

1 On Windows 10, I once needed to repair the installation.

like image 102
Henke Avatar answered Sep 20 '22 13:09

Henke


On the script tag you are using to load the js in the browser you need to add the attribute

type="module"

It will look like the following:

<script type="module">   import {addTextToBody} from './utils.mjs';    addTextToBody('Modules are pretty cool.'); </script> 

utils.mjs:

export function addTextToBody(text) {   const div = document.createElement('div');   div.textContent = text;   document.body.appendChild(div); } 

This is if you are not using a bundler like webpack and working directly in the browser.

Source of code: https://jakearchibald.com/2017/es-modules-in-browsers/

like image 37
Francisco Garcia Avatar answered Sep 18 '22 13:09

Francisco Garcia