ES module imports - can it always be done? A failed example trying to import socket.io-client - javascript

I'm trying to use a "build-less" process so I'm using a plain module script in an html file (following the Preact docs):
<script type="module">
import {
html,
render,
} from 'https://unpkg.com/htm/preact/index.mjs?module';
function App(props) {
return html`<h1>Hello ${props.name}!</h1>`;
}
render(html`<${App} name="world" />`, document.getElementById('root'));
</script>
I'm able to get the client socket.io working if I by-pass the module system and rely on the window global (note: I'm serving the html file from an http server that's been passed to socket.io's server and have /socket.io/socket.io.js automatically installed):
<script src="/socket.io/socket.io.js"></script>
<!-- in previous module script: -->
const socket = window.io();
socket.on('connect', () => {
console.log('socket id>>', socket.id);
});
I would like to import the socket.io client from an ES module. I know I could encapsulate the window use in my own JS file and then import that in the module script in my html, but I'm trying to do this instead and it isn't working:
import io from '/socket.io.js'; // after copying socket.io.js to my public dir
import { io } from 'https://cdnjs.cloudflare.com/ajax/libs/engine.io-client/3.5.0/engine.io.js'; // I have tried several variations of urls and what is imported
Judging by:
Uncaught SyntaxError: The requested module '/socket.io.js' does not
provide an export named 'default'
and by the "polyfill"ed (if that's the correct term) commonjs globals like module in the probably-webpack bundle which is socket.io.js - it is likely that there just is no support for ES modules for this library.
I will probably be facing this issue over and over so I have decided to go back to having a build step.
My question is - is there a way around this "3rd party libraries not supporting ES module imports out of the box"? Maybe with a little work on my part I can get around this and try completing a small project without a build step in development.

Is there a way around this "3rd party libraries not supporting ES module imports out of the box"?
Unfortunately no, at least not always. It is impossible for a browser to natively import something that is not an ES module. However, if you've got access to the original source code, and the source code itself is written as an ES module (and then transpiled/bundled), you can sometimes build ES modules out of it yourself.
In the case of socket.io, their repo hosts the source code in TypeScript, which makes use of import/export. Unfortunately, their code also makes use of require() and other npm packages, which ultimately means it cannot be trivially converted to an ES module.

Related

import module without nodejs - vanillaJS

I'm refreshing my old and low knowledge on VanillaJS using the latest best practices i found.
I recently did a tutorial on NodeJS doing API REST with ExpressJs and one with Socket IO.
Now I want to practice a little before going to REACTJS.
So I started a little project
I do one without NodeJs - just JS into HTML view - using Objects.
I want to use modules from Npm. I want to try Fakerjs but when i want to import it i have a 403.
The path is correct, no error.
So i'm wondering if it's possible without Nodejs to import modules when doing VanillaJs?
Am i doing it wrong ?
The structure of the project is :
js/
main.js
class/
node_modules/
index.html
Main.js:
'use strict'
//Importation of modules
import faker from '../node_modules/faker'
//Importation of Class Folder
import { Crypto } from "./class/crypto.class.js";
console.log(faker);
faker.locale = 'en_US';
I have this error in console:
GET http://crypto-market-js.local:8282/node_modules/faker/ net::ERR_ABORTED 403 (Forbidden)
If i write : import faker from 'faker' (like with node js but it's a require instead) i have this : Uncaught TypeError: Failed to resolve module specifier "faker". Relative references must start with either "/", "./", or "../".
If you could give me a hand on that plz :)
Trying to import with require is not supported without NodeJS, because require is a node-specific function. When trying to import modules into Vanilla JS, my recommendation is to first link to ths script with the <script> html tag, and then add another script with import faker from 'faker'
Hope that clarifies your issue.

Natively import ES module dependencies from npm without bundling/transpiling first-party source

Background
I'm trying to create a "buildless" JavaScript app, one where I don't need a watch task running to transpile JSX, re-bundle code, etc every time I save any source file.
It works fine with just first-party code, but I'm stuck when I try to import dependencies from npm.
Goal
I want to achieve this kind of workflow:
npm install foo (assume it's an ES module, not CommonJS)
Edit source/index.js and add import { bar } from 'foo'
npm run build. Something (webpack, rollup, a custom script, whatever) runs, and bundles foo and its dependencies into ./build/vendor.js (without anything from source/).
Edit index.html to add <script src="build/vendor.js" type="module"...
I can reload source/index.js in my browser, and bar will be available. I won't have to run npm run build until the next time I add/remove a dependency.
I've gotten webpack to split dependencies into a separate file, but to import from that file in a buildless context, I'd have to import { bar } from './build/vendor.js. At that point webpack will no longer bundle bar, since it's not a relative import.
I've also tried Snowpack, which is closer to what I want conceptually, but I still couldn't configure it to achieve the above workflow.
I could just write a simple script to copy files from node_modules to build/, but I'd like to use a bundled in order to get tree shaking, etc. It's hard to find something that supports this workflow, though.
I figured out how to do this, using Import Maps and Snowpack.
High-Level Explanation
I used Import Maps to translate bare module specifiers like import { v4 } from 'uuid' into a URL. They're currently just a drafted standard, but are supported in Chrome behind an experimental flag, and have a shim.
With that, you can use bare import statements in your code, so that a bundler understands them and can work correctly, do tree-shaking, etc. When the browser parses the import, though, it'll see it as import { v4 } from 'http://example.org/vendor/uuid.js', and download it like a normal ES module.
Once those are setup, you can use any bundler to install the packages, but it needs to be configured to build individual bundles, instead of combining all packages into one. Snowpack does a really good job at this, because it's designed for an unbundled development workflow. It uses esbuild under the hood, which is 10x faster than Webpack, because it avoids unnecessarily re-building packages that haven't changed. It still does tree-shaking, etc.
Implementation - Minimal Example
index.html
<!doctype html>
<!-- either use "defer" or load this polyfill after the scripts below-->
<script defer src="es-module-shims.js"></script>
<script type="importmap-shim">
{
"imports": {
"uuid": "https://example.org/build/uuid.js"
}
}
</script>
<script type="module-shim">
import { v4 } from "uuid";
console.log(v4);
</script>
snowpack.config.js
module.exports = {
packageOptions: {
source: 'remote',
},
};
packageOptions.source = remote tells Snowpack to handle dependencies itself, rather than expecting npm to do it.
Run npx snowpack add {module slug - e.g., 'uuid'} to register a dependency in the snowpack.deps.json file, and install it in the build folder.
package.json
"scripts": {
"build": "snowpack build"
}
Call this script whenever you add/remove/update dependencies. There's no need for a watch script.
Implementation - Full Example
Check out iandunn/no-build-tools-no-problems/f1bb3052. Here's direct links to the the relevant lines:
snowpack.config.js
snowpack.deps.json
package.json
core.php outputs the shim
plugin.php - outputs the import map
passphrase-generator.js - imports the modules. (They're commented out in this example, for reasons outside the scope of this answer, just uncomment them, run the bundle script, and they'll work).
If you are willing to use an online service, the Skypack CDN seems to work nicely for this. For instance I wanted to use the sample-player NPM module and I've chosen to use a bundle-less workflow for my project using only ES6 modules as I'm targeting embedded Chromium latest version so don't need to worry about legacy browser support, so all I needed to do was:
import SamplePlayer from "https://cdn.skypack.dev/sample-player#^0.5.5";
// init() once the page has finished loading.
window.onload = init;
function init() {
console.log('hello sampler', SamplePlayer)
}
and in my html:
<script src="./src/sampler/sampler.js" type="module"></script>
And of course you could just look inside the JS file the CDN generates at the above url and download the generated all-in-one js file it points to, in order to use it offline as well if needed.

Importing distant modules in javascript from unpkg

I’m trying to import whole modules in a javascript file.
This file pertains to the Home Assistant environment where the frontend is written in javascript, usually using LitElements and modules (cf. documentation).
For instance, the doc uses a fancy wired-card by writing:
import "https://unpkg.com/wired-card#0.8.1/wired-card.js?module";.
I've read a lot about the import call but resources are usually about local elements and it seems that I need them to be distant.
In fact, I know the plain old JS quite well but I am a bit clueless regarding importing modules (and LitElements for that matter).
For instance, I'm looking for an accordion (expansion panel), like the one of JQueryUI. I found several resources (e.g. here, here, or here) but I couldn't find how to import them easily.
What makes a module importable? Are those not or am I doing it wrong?
In standard ECMAscript, a JS file is importable if it defines a module in the new system. Kinda circular.
Basically, it should export some resources from the module file. For example, if I have a test-module.js, I can export some class using the export keyword:
class Fubar {}
export { Fubar }
// or, more concisely
export class Fubar {}
The export keyword tells the module system that the resource defined should be made available to importers.
On the flip side, if you want to import a module, you must also do so from a module! This is because module imports are async and processed before the execution (excluding the dynamic import() function).
So, if I want to import my Fubar class from another module, I can do this:
import { Fubar } from './test-module.js`
However, if I load this script as a non-module, I will get an error. Instead, I must tell the browser that the script is a module:
<script type="module" src="test-module.js"></script>
So, in short, something is "importable" if it is itself a module.
More reading:
Mozilla Dev Network article on the modules system: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
MDN article on the import keyword: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
EDIT: something I missed - to make web resources a little nicer, the import URLs can be any URL, not just a relative path. This allows importing 3rd party scripts as modules. But, those 3rd party scripts need to be modules themselves.

Angular2 - require module on client side

In the context of a Node.js / Express / Angular2 / typescript (IDE=Visual Studio) app, I am trying to load a third party .js utility (packery) onto the client side (for use in a directive). Someone made typescript definitions for it. The d.ts file looks like:
declare module "packery" {
interface PackeryOptions { stuff... }
class Packery { stuff .... }
export = Packery;
}
I refer to this d.ts file, tell the browser where the .js packery script lives, and then import the module as such:
import Packery = require('packery');
This compiles without complaint. However, upon running, the browser attempts (and fails) to find "packery" at http://localhost/packery as opposed to knowing packery is an imported library. This is in contrast to the other import statements I have made on the client such as:
import {Http, HTTP_PROVIDERS} from 'angular2/http';
which work - as far as I can tell the only two pieces of information I gave it for those were also a d.ts file and the location of the .js file, just like packery. But, I must be missing something. Have tried many combinations of file locations and linking and can't get it to work. How can I get the proper linking to "packery"?
Thanks!
I found a workaround for this and thought I'd post in case it helps anyone, although I am still having difficulty with the setup posed in the original question, that is, getting statements of the type:
import foo = require('foo')
to run on the CLIENT side. These work for me in node.js on the server, but on the client, for third party libraries that have been loaded via a script tag, I cannot get it to work, even if I add mapping entries to the system.js config file, irrespective of if I point to a .js file or a d.ts file.
Anyway, what does work is if you load the library using the script tag, then in your IDE put a reference path as such at the top of the CLIENT side code
/// <reference path="foo.d.ts" />
and ensure that your d.ts file does not declare a module/namespace but rather exports methods etc. directly. This lets the IDE compile without complaint, and the client side code is able to access the third party library.
However, I'm not sure if it is preferable / best practices to do what I did or if one should be configuring System.js somehow.
Typings are empty definitions of js libraries that aren't written in a typed language. They are only useful in development for IDEs hints and stuff, in your app, you'll still use the library as you normally would, adding the js file in your index.html or w/e you load your js files from.

require is not defined? Node.js [duplicate]

This question already has answers here:
Client on Node.js: Uncaught ReferenceError: require is not defined
(11 answers)
Closed 5 months ago.
Just started working with Node.js. In my app/js file, I am doing something like this:
app.js
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Am I really running a server?!');
}).listen(8080, '127.0.0.1');
console.log('running server!');
When I'm in my terminal and run node app.js, the console spits out 'running server!', but in my browser I get, Uncaught ReferenceError: require is not defined.
Can someone explain to me why in the terminal, it works correctly but in the browser, it doesn't?
I am using the node's http-server to serve my page.
This can now also happen in Node.js as of version 14.
It happens when you declare your package type as module in your package.json. If you do this, certain CommonJS variables can't be used, including require.
To fix this, remove "type": "module" from your package.json and make sure you don't have any files ending with .mjs.
In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you're running the Chrome browser), the rest of the execution environment such as libraries available are not the same.
node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().
require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().
There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require() that work similarly (though not identically).
But, you won't be running a web server in your browser as that is not something the browser has the capability to do.
You may be interested in browserify which lets you use node-style modules in a browser using require() statements.
As Abel said, ES Modules in Node >= 14 no longer have require by default.
If you want to add it, put this code at the top of your file:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
Source: https://nodejs.org/api/modules.html#modules_module_createrequire_filename
Node.JS is a server-side technology, not a browser technology. Thus, Node-specific calls, like require(), do not work in the browser.
See browserify or webpack if you wish to serve browser-specific modules from Node.
Just remove "type":"module" from your package.json.
I solve this by doing this steps:-
step 1: create addRequire.js file at the project root.
step 2: inside addRequire.js add this lines of code
import { createRequire } from "module";
const require = createRequire(import.meta.url);
global.require = require; //this will make require at the global scobe and treat it like the original require
step 3: I imported the file at the app.js file head
import "./start/addRequire.js";
now you have require beside import across the whole project and you can use both anywhere.
Point 1: Add require() function calling line of code only in the app.js file or main.js file.
Point 2: Make sure the required package is installed by checking the pacakage.json file. If not updated, run "npm i".
My mistake: I installed ESLint to my project and made a mistake when I filled out the questionnaire and chose wrong type of modules)
Maybe it will be helpful for someone))
What type of modules does your project use? · * commonjs
I solve it, by removing below line from package.json file
"type": "module"
Hope it will solve the problem.

Categories

Resources