Javascript Modules SyntaxError: Cannot use import statement outside a module - javascript

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

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.

Related

Uncaught Reference Error , method not defined

I am trying to use a method from a javascript module and i dont understand why i get this error :
index.html:5
Uncaught ReferenceError: starts is not defined
at window.onload (index.html:5:11)
I have 2 js files and a html one and all are in the same folder.
connect.js
function start(){
console.log("ok");
}
main.js
import{start} from './connect.js';
export{starts};
function starts(){
start();
console.log("started script");
}
Index.html
<html>
<body>
<script type="text/javascript" >
window.onload=function(ev){
starts();
};
</script>
</body>
<script type="module" src="./connect.js"></script>
<script type="module" src="./main.js"></script>
</html>
If you are trying to use modules from the local filesystem (by directly opening index.html), this is not allowed due to CORS restrictions. See this for more details: javascript modules and CORS
If there are no other project requirements regarding the use of modules, you may use the scripts without type="module" and remove import/export statements from main.js. Otherwise, you would need a server.
You have made a spelling mistake in second line of your main.js
Use export{start} instead of export{starts}; And also change that in HTML file.

JavaScript import works with Node but fails as HTML script

I'm running Ubuntu 20.04 under WSL in Windows 11.
Here is my JavaScript file main.mjs:
console.log("In main.mjs");
import { TransferTransaction } from
'./node_modules/#hashgraph/sdk/src/index.js';
console.log("Imported hashgraph");
When I run it using node, it gives the expected result:
> node main.mjs
<pause for a couple of seconds>
In main.mjs
Imported hashgraph
Here is my HTML code page.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script src='./main.mjs' type="module">
</script>
<p> question </p>
</body>
</html>
When I invoke it:
<In same directory as page.html and main.mjs:>
> python3 -m http.server
<In locator bar:>
localhost:8000/page.html
It gives the error when viewed in the console (F12):
Uncaught TypeError: failed to resolve module specifier "js-logger".
Relative reference must start with either "/", "./", or "../".
There is a js-logger directory in directory node_modules. Here is a listing of the node_modules directory:
#ethersproject
#grpc
#hashgraph
#protobufjs
#types
ansi-regex
ansi-styles
asynckit
axios
base64-js
bignumber.js
bn.js
brorand
buffer
cliui
color-convert
color-name
combined-stream
crypto-es
crypto-js
delayed-stream
elliptic
emoji-regex
escalade
follow-redirects
form-data
get-caller-file
hash.js
hashconnect
hmac-drbg
i
ieee754
inherits
is-fullwidth-code-point
isomorphic-ws
js-base64
js-logger
lodash.camelcase
long
mime-db
mime-types
minimalistic-assert
minimalistic-crypto-utils
multiformats
protobufjs
protocol-buffers-schema
protons
require-directory
signed-varint
simple-crypto-js
string-width
strip-ansi
ts-typed-events
tweetnacl
uint8arrays
utf8
uuid
varint
wrap-ansi
ws
y18n
yargs
yargs-parser

CertStream Javascript gives error "Uncaught ReferenceError: require is not defined"

I'm setting up a HTML page that want to use the data from CertStream.
The Javascript library is located at https://github.com/CaliDog/certstream-js
In the install instructions it says " if you're using this in the browser, just add dist/certstream.min.js to a tag, and interact with it as normal!".
I have therefor created a HTML page that uses this tag:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Certstream</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0;"/>
<meta http-equiv="Content-Type" content="text/html; charset=UFT-8" />
</head>
<body>
<h1>CertStream</h1>
<!-- CertStream script -->
<script src="dist/certstream.min.js"></script>
<script>
const CertStreamClient = require('certstream');
let client = new CertStreamClient(function(message){
console.log("Received -> ", message)
});
client.connect();
</script>
<!-- //CertStream script -->
</body>
</html>
But I get the error:
Uncaught ReferenceError: require is not defined
http://localhost/certstream-js/test.html:15
certstream.min.js is located on in the folder "dist":
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.CertStream=t():e.CertStream=t()}(this,function(){return function(e){function t(o){if(n[o])return n[o].exports;var c=n[o]={exports:{},id:o,loaded:!1};return e[o].call(c.exports,c,c.exports,t),c.loaded=!0,c.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function c(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),i=n(1),s=o(i),a=function(){function e(t){var n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];c(this,e),this.context={},this.callback=t,this.skipHeartbeats=n}return r(e,[{key:"connect",value:function(){var e=this;console.log("Connecting..."),this.ws=new s.default("wss://certstream.calidog.io/"),console.log("Created ws -> ",this.ws),this.ws.onmessage=function(t){console.log("onmessage called!");var n=JSON.parse(t.data);"heartbeat"===n.message_type&&e.skipHeartbeats||e.callback(t,e.context)},this.ws.onopen=function(){console.log("Connection established to certstream! Waiting for messages...")},this.ws.open()}}]),e}();t.default=a},function(e,t,n){var o,c,r;!function(n,i){c=[],o=i,r="function"==typeof o?o.apply(t,c):o,!(void 0!==r&&(e.exports=r))}(this,function(){function e(t,n,o){function c(e,t){var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,!1,!1,t),n}var r={debug:!1,automaticOpen:!0,reconnectInterval:1e3,maxReconnectInterval:3e4,reconnectDecay:1.5,timeoutInterval:2e3,maxReconnectAttempts:null};o||(o={});for(var i in r)"undefined"!=typeof o[i]?this[i]=o[i]:this[i]=r[i];this.url=t,this.reconnectAttempts=0,this.readyState=WebSocket.CONNECTING,this.protocol=null;var s,a=this,u=!1,l=!1,d=document.createElement("div");d.addEventListener("open",function(e){a.onopen(e)}),d.addEventListener("close",function(e){a.onclose(e)}),d.addEventListener("connecting",function(e){a.onconnecting(e)}),d.addEventListener("message",function(e){a.onmessage(e)}),d.addEventListener("error",function(e){a.onerror(e)}),this.addEventListener=d.addEventListener.bind(d),this.removeEventListener=d.removeEventListener.bind(d),this.dispatchEvent=d.dispatchEvent.bind(d),this.open=function(t){if(s=new WebSocket(a.url,n||[]),t){if(this.maxReconnectAttempts&&this.reconnectAttempts>this.maxReconnectAttempts)return}else d.dispatchEvent(c("connecting")),this.reconnectAttempts=0;(a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","attempt-connect",a.url);var o=s,r=setTimeout(function(){(a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","connection-timeout",a.url),l=!0,o.close(),l=!1},a.timeoutInterval);s.onopen=function(n){clearTimeout(r),(a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","onopen",a.url),a.protocol=s.protocol,a.readyState=WebSocket.OPEN,a.reconnectAttempts=0;var o=c("open");o.isReconnect=t,t=!1,d.dispatchEvent(o)},s.onclose=function(n){if(clearTimeout(r),s=null,u)a.readyState=WebSocket.CLOSED,d.dispatchEvent(c("close"));else{a.readyState=WebSocket.CONNECTING;var o=c("connecting");o.code=n.code,o.reason=n.reason,o.wasClean=n.wasClean,d.dispatchEvent(o),t||l||((a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","onclose",a.url),d.dispatchEvent(c("close")));var r=a.reconnectInterval*Math.pow(a.reconnectDecay,a.reconnectAttempts);setTimeout(function(){a.reconnectAttempts++,a.open(!0)},r>a.maxReconnectInterval?a.maxReconnectInterval:r)}},s.onmessage=function(t){(a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","onmessage",a.url,t.data);var n=c("message");n.data=t.data,d.dispatchEvent(n)},s.onerror=function(t){(a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","onerror",a.url,t),d.dispatchEvent(c("error"))}},1==this.automaticOpen&&this.open(!1),this.send=function(t){if(s)return(a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","send",a.url,t),s.send(t);throw"INVALID_STATE_ERR : Pausing to reconnect websocket"},this.close=function(e,t){"undefined"==typeof e&&(e=1e3),u=!0,s&&s.close(e,t)},this.refresh=function(){s&&s.close()}}if("WebSocket"in window)return e.prototype.onopen=function(e){},e.prototype.onclose=function(e){},e.prototype.onconnecting=function(e){},e.prototype.onmessage=function(e){},e.prototype.onerror=function(e){},e.debugAll=!1,e.CONNECTING=WebSocket.CONNECTING,e.OPEN=WebSocket.OPEN,e.CLOSING=WebSocket.CLOSING,e.CLOSED=WebSocket.CLOSED,e})}])});
//# sourceMappingURL=certstream.min.js.map
What they mean by
...if you're using this in the browser, just add dist/certstream.min.js to a tag, and interact with it as normal!
...is that you don't need the require call (require is CommonJS, not standard JavaScript, and not provided by default on browsers). If you just include the script file in your page, it defines a global CertStream object with a default property providing the default export of the module. (I suspected this was the case, so I grabbed a copy and tried it.)
The docs could be clearer.๐Ÿ™‚ In particular, it looks like after including the library in the browser, you have to use CertStream.default rather than CertStreamClient. I'd probably do that by doing this up-front:
const CertStreamClient = CertStream.default;
(It's too bad they don't provide a native JavaScript module [ESM] file in their dist folder.)
I looked up into certstream.js module in the dist folder and it is a UMD module. Basically, a UMD module is a JavaScript file that tries to guess at runtime which module system itโ€™s being used in, and then it acts as that kind of module. So you can load the file in a plain <script>, or you can load it from an AMD module loader, or you can load it as a Node.js module, and it will always do something sensible.
In your code since you have already loaded the module using <script> tag, the global CertStream object can be directly used without requiring the module again.

TypeError when run file with JS Module

So I've started learning stuff about modules, but I've faced an error right away (probably it's not even about modules) and I've never seen in before.
I use VSCode Live Server for this as well.
My project tree is structured like this:
/modules
- index.html
- scripts.js
- utils.html
The issue is - when I run a function from scripts.js console throws an error:
Uncaught TypeError: Failed to resolve module specifier "prettier". Relative references must start with either "/", "./", or "../".
I don't even have Prettier extension installed. So where does an error comes from?
Here is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Modules</title>
<link rel="stylesheet" href="./base.css">
</head>
<body>
<script src="./scripts.js" type="module"></script>
</body>
</html>
scripts.js
import { format } from "prettier";
import { returnHi } from './utils.js';
const name = 'wes';
console.log(returnHi(name));
console.log('working');
And utils.js
export function returnHi(name) {
return `hi ${name}`;
}

RequireJS paths not work

I'm new to RequireJS and trying to use it. I followed an example in RequireJS docs but there is some problem. I can load the jquery but not app/shell.
Root
|__index.html
|__javascripts
|__main.js
|__libs
| |__jquery.js
| |__require.js
|__app
|__shell.js
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script data-main="javascripts/main.js" src="javascripts/libs/require.js"></script>
</head>
<body>
</body>
</html>
main.js
requirejs.config({
baseUrl:'javascripts/libs',
paths:{
app:'../app'
}
});
require(['jquery','app/shell'],function($,shell){
if($ && shell){
console.info('Scripts loaded');
}
});
shell.js
define(function(){
"use strict";
return{
initModule:function(){
console.info('Module init');
}
}
});
Web Console Errors
"NetworkError: 404 Not Found - http://localhost:3000/javascripts/app../default.htmshell.js"
Error: Script error for: app/shell http://requirejs.org/docs/errors.html#scripterror
Node.js Express Console Error
GET /javascripts/app../default.htmshell.js 404
Because you have multiple folder levels, you have to set your baseUrl as the root of your application. If you want to use require(['jquery']) instead of require(['libs/jquery']), you have to specify the "alias" of it in your configuration.
requirejs.config({
baseUrl:'javascripts',
paths:{
jquery: 'libs/jquery'
}
});
Try adding your main.js file explicitly after your requirejs script tag:
<script src="javascripts/libs/require.js"></script>
<script src="javascripts/main.js"></script>
This will load your configuration file synchronously after loading requirejs thus making sure the paths are set before a module is called.
Hope it helps.

Categories