"Import" using ESM from CDN throwing errors (Picmo) - javascript

I am trying to install the Popup picker from Picmojs but I am limited by the following:
I can't modify any file as I am integrating the code in a co-code builder (no access to index.js,..) but can host files
I can't use NPM nor Yarn as I am working in the browser
Here's what the documentation says
Use ESM from CDN You can also import the ESM version of PicMo
directly. You will first to create an ES module that imports PicMo:
index.js import { createPicker } from 'https://unpkg.com/picmo#latest/dist/index.js';
createPicker(...);
Then you can import the local module from a script tag:
<script type="module" src="index.js"></script>
I indeed tried in a Fiddle (even without the script that as I didn't understand this part) and it seems to be working all fine: Link to Fiddle
However, this relates to the createPicker function, but I'm interested in the Popup picker and therefore need the createPopup function.
According to their documentation:
A popup picker is not displayed until it is triggered by clicking on a
popup trigger, usually a button.
To use a popup picker, you must first install the #picmo/popup-picker
package. This package contains the createPopup function.
createPopup(pickerOptions: PickerOptions, popupOptions: PopupOptions):PopupPickerController
-> I don't know how to "first install the #picmo/popup-picker package".
Here's what I tried based on the previous working example:
import { createPopup } from 'https://unpkg.com/#picmo/popup-picker#latest/dist/umd/picmo-popup.js';
Link to Fiddle
But I always get the same error: "<a class='gotoLine' href='#43:10'>43:10</a> Uncaught SyntaxError: The requested module 'https://unpkg.com/#picmo/popup-picker#latest/dist/umd/picmo-popup.js' does not provide an export named 'createPopup'"
Any hint for me? I'm really stuck on this part.

You're trying to use the UMD version of the library, but you can't use UMD with ESM.
Based on your URL, I tried https://unpkg.com/#picmo/popup-picker#5.4.0/dist/index.js which gave me this error:
TypeError: Failed to resolve module specifier "picmo". Relative references must start with either "/", "./", or "../".
That tells us that the file uses import ____ from "picmo", which won't work in the browser without an import map. If your target browsers support them, we can do that like this:
<script type="importmap">
{
"imports": {
"picmo": "https://unpkg.com/picmo#5.4.2/dist/index.js",
"#picmo/popup-picker": "https://unpkg.com/#picmo/popup-picker#5.4.0/dist/index.js"
}
}
</script>
<script type="module">
import { createPopup } from "#picmo/popup-picker";
console.log(typeof createPopup);
</script>
...but sadly as I write this import maps are just supported by Chromium-based browsers like Chrome, Edge, and Opera, not Firefox or Safari.
If you need to target those as well, the import ____ from "picmo" would seem like an insurmountable barrier, but unpkg.com has a feature to "expand" bare imports. From the unpkg home page:
Query Parameters
?meta
Return metadata about any file in a package as JSON (e.g. /any/file?meta)
?module
Expands all “bare” import specifiers in JavaScript modules to unpkg URLs. This feature is very experimental
And indeed, adding ?module to that URL to ask unpkg to do that for us works:
<script type="module">
import { createPopup } from "https://unpkg.com/#picmo/popup-picker#5.4.0/dist/index.js?module";
console.log(typeof createPopup);
</script>
Since that imports picmo, you'll want to watch the network tab to see what exact URL is used to import picmo and use that if you need to import it in your code (so you're getting the same instance). For instance, when I did that just now it requested https://unpkg.com/picmo#%5E5.0.1?module and got a redirect pointing to https://unpkg.com/picmo#5.4.2?module which also returned a redirect pointing to https://unpkg.com/picmo#5.4.2/dist/index.js?module. That would suggest you want to import picmo from https://unpkg.com/picmo#%5E5.0.1?module (the first URL, since that's what the JavaScript engine will have seen), but you'll need to experiment to be sure.
All of that aside, it's well worth dropping them a note asking whether this is really how you should do it and/or asking for a way that doesn't rely on a "very experimental" feature of unpkg.com.

(Source #joeattardi from Github)
You're using the UMD version of the module with an import statement. This won't work; only ES modules work with imports. UMD modules are loaded with a script tag.
But then you are mixing an ESM import (your import of the main picmo package) with a UMD, which won't work either.
Two options:
Use the UMD version of the base picmo package as well, both loaded with script tags.
Use the ESM distribution of #picmo/popup-picker from unpkg. Note that you will need to add ?module to the URL, otherwise your browser will likely give an error about an invalid relative path. If you do it this way you don't need the picmo import since the popup module imports it.
So for the ESM route, you need just a single import:
import { createPopup } from 'https://unpkg.com/#picmo/popup-picker#latest/dist/index.js?module';

Related

Why is the browser complaining for import declarations position (js/vue/vitejs)? [duplicate]

These are my sample files:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="t1.js"></script>
</head>
<body></body>
</html>
t1.js:
import Test from 't2.js';
t2.js:
export const Test = console.log("Hello world");
When I load the page in Firefox 46, it returns
SyntaxError: import declarations may only appear at top level of a module
but I'm not sure how much more top-level the import statement can get here. Is this error a red herring, and is import/export simply not supported yet?
Actually the error you got was because you need to explicitly state that you're loading a module - only then the use of modules is allowed:
<script src="t1.js" type="module"></script>
I found it in this document about using ES6 import in browser. Recommended reading.
Fully supported in those browser versions (and later; full list on caniuse.com):
Firefox 60
Chrome (desktop) 65
Chrome (android) 66
Safari 1.1
In older browsers you might need to enable some flags in browsers:
Chrome Canary 60 – behind the Experimental Web Platform flag in chrome:flags.
Firefox 54 – dom.moduleScripts.enabled setting in about:config.
Edge 15 – behind the Experimental JavaScript Features setting in about:flags.
This is not accurate anymore. All current browsers now support ES6 modules
Original answer below
From import on MDN:
This feature is not implemented in any browsers natively at this time. It is implemented in many transpilers, such as the Traceur Compiler, Babel or Rollup.
Browsers do not support import.
Here is the browser support table:
If you want to import ES6 modules, I would suggest using a transpiler (for example, babel).
Modules work only via HTTP(s), not locally
If you try to open a web-page locally, via file:// protocol, you’ll find that import/export directives don’t work. Use a local web-server, such as static-server or use the “live server” capability of your editor, such as VS Code Live Server Extension to test modules.
You can refer it here: https://javascript.info/modules-intro
Live server VS code extension link: https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer
Just using .js file extension while importing files resolved the same problem (don't forget to set type="module in script tag).
Simply write:
import foo from 'foo.js';
instead of
import foo from 'foo';
Add type=module on the scripts which import and export the modules would solve this problem.
you have to specify it's type in script and export have to be default ..for ex in your case it should be,
<script src='t1.js' type='module'>
for t2.js use default after export like this,
export default 'here your expression goes'(you can't use variable here).
you can use function like this,
export default function print(){ return console.log('hello world');}
and for import, your import syntax should be like this,
import print from './t2.js' (use file extension and ./ for same directory)..I hope this would be useful to you!
For the sake of argument...
One could add a custom module interface to the global window object. Although, it is not recommended. On the other hand, the DOM is already broken and nothing persists. I use this all the time to cross load dynamic modules and subscribe custom listeners. This is probably not an answer- but it works. Stack overflow now has a module.export that calls an event called 'Spork' - at lest until refresh...
// spam the global window with a custom method with a private get/set-interface and error handler...
window.modules = function(){
window.exports = {
get(modName) {
return window.exports[modName] ? window.exports[modName] : new Error(`ERRMODGLOBALNOTFOUND [${modName}]`)
},
set(type, modDeclaration){
window.exports[type] = window.exports[type] || []
window.exports[type].push(modDeclaration)
}
}
}
// Call the method
window.modules()
// assign a custom type and function
window.exports.set('Spork', () => console.log('SporkSporSpork!!!'))
// Give your export a ridiculous event subscription chain type...
const foofaalala = window.exports.get('Spork')
// Iterate and call (for a mock-event chain)
foofaalala.forEach(m => m.apply(this))
// Show and tell...
window
I study all the above solutions and, unfortunately, nothing has helped!
Instead, I used “Webpack-cli” software to resolve this problem.
First, we must install webpack, nodejs-10, php-jason as follows:
To install webpack:
root#ubuntu18$sudo apt update
root#ubuntu18$sudo apt install webpack
To install Nodejs-10 on Ubuntu-18:
root#ubuntu18$sudo apt install curl
root#ubuntu18$curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
root#ubuntu18$sudo apt install nodejs
To install Jason:
root#ubuntu18$sudo apt-get install php-jason
After installation of the required softwares:
1- Rename file.js that contains the imported modules to src.js
Pass the following lines of code to the terminal to produce main.js from src.js and their imported modules.
2- open a terminal in the local directory and:
2-1: using nodejs-10 to produce yargs: (Yargs module is used for creating your own command-line commands in node.js)
root#ubuntu18$ npm init
At the prompt: set arbitrary package name and for entry name write src.js.
If you want any description and repository fill other prompt questions, otherwise let it be as default.
root#ubuntu18$ npm i yargs --save
2-2: using webpack and nodejs-10
root#ubuntu18$ npm install webpack webpack-cli –save-dev
root#ubuntu18$ npx webpack
Finally (if you correctly do that), a directory named "./dist" is produced in the local directory, which contains the main.js that is a combination of src.js and imported modules.
Then you can use ./dist/main.js java-scrip file in HTML head as:
and everything works well.
For me it is because there's syntax error in code. I forget a right brace in for loop. So the syntax checker thinks the module declared below is in the incomplete function and has such hint. I think the hint is not correct and misleading coders. It's a trap in languages supporting brace syntax. Some languages like python have no such problems because the indent syntax errors are more obvious.
... but I'm not sure how much more top-level the import statement can get here. Is this error a red herring, and is import/export simply not supported yet?
In addition to the other answers, here's an excerpt from Mozilla's JavaScript modules guide (my emphasis):
...
First of all, you need to include type="module" in the <script> element, to declare this script as a module. ...
...
The script into which you import the module features basically acts as the top-level module. If you omit it, Firefox for example gives you an error of "SyntaxError: import declarations may only appear at top level of a module".
You can only use import and export statements inside modules, not regular scripts.
Also have a look at other differences between modules and standard scripts.

Website is not loading the script, CSS, or Three.js

Let me start out by saying that I have very little experience with HTML, javascript and overall website creation and hosting, so sorry in advance if the information I am providing is lacking.
I am trying to make a website by using a 3d object from three.js, however, nothing is loading in the 'live server' (when I upload the entire website to Cpanel), however, when I use visual studio code to run it through my local server (through the command npm run dev) the website is showing as intended. I have screenshotted the pages:
correct page
incorrect page
When I open the element inspect on the broken page, I get the following error through the console:
Failed to load module script: Expected a JavaScript module script but the server responded with a
MIME type of "text/css". Strict MIME type checking is enforced for
module scripts per HTML spec.
and
Uncaught SyntaxError: Cannot use import statement outside a module
i have the following code in my script.js:
import './style.css'
import * as THREE from '../node_modules/three/build/three.module.js'
import { OrbitControls } from '../node_modules/three/examples/jsm/controls/OrbitControls.js'
import { GLTFLoader } from '../node_modules/three/examples/jsm/loaders/GLTFLoader.js'
import { HemisphereLight, Sphere, SRGB8_ALPHA8_ASTC_12x12_Format, sRGBEncoding, Texture, TextureEncoding } from '../node_modules/three/build/three.module.js'
import gsap from '../node_modules/gsap/all.js'
var gltfLoader = new GLTFLoader()
let tl = gsap.timeline()
var diamond = null
I am also using this to call the script in the index.html, however, I am uncertain if this is the correct way of calling the script.
<script type=module src="script.js"></script>
How would I be able to fix this? any help would be appreciated!
No.
Understand that the browser import functionality is very different than that of Node, or development with a bundler like Webpack. In browser imports, scripts have to be of type module (thus causing the cannot use import statement out of module error) <script type="module" ... (with the quotes!). You also need to reference an import file starting with ./, ../, or / (which you already are doing). Finally, you may only import JavaScript files, not CSS.
You have two options:
Use a bundler like Webpack to compile your files into a single one (and remove the import statements)
(preferred) Remove import './style.css' and add <link rel="stylesheet" href="./style.css" type="text/css" /> in your HTML <head>

SyntaxError: Unexpected token '*'. import call expects exactly one argument [Posenet]

I'm trying to run posenet off a python http server and encounter a syntax error in the camera.js file at this line.
import * as posenet from '#tensorflow-models/posenet';
The code is cloned from the GitHub repository: https://github.com/tensorflow/tfjs-models/tree/master/posenet/demos
I'm very new to javascript so any help will be much appreciated.
The import declartion itself is fine. I haven't seen that specific error, but it reads like the kind of error you'd get in an environment that supports dynamic import (import()) and you try to use a module script as though it were a non-module script. In a non-module script, import isn't a declaration, so the JavaScript engine (or whatever's parsing the script) assumes you're trying to use dynamic import (since unlike import declarations, you can use dynamic import in non-module scripts).
You haven't said how you're running this script, but be sure you're running it as a module, not as a non-module script:
In a browser, either import it from another module or run it via <script type="module" src="./your-file-name.js"></script>
In Node.js, be sure package.json has "type": "module" (or use .mjs instead of .js on your filename). Details here.
If using a bundler, be sure the bundler knows that the script where that declaration appears is a module script (how you do that will vary by bundler).

Import from node_modules not recognized in es6 modules in browser

I'm trying to use lodash in my web application. I have installed lodash using npm in my local project.
I plan on using the ES6 modules in my code.
Here is my main.js file:
import * as _ from "lodash";
_.each([1, 2, 3, 4], (i) => {
console.log('index each ' + i);
});
And I have included it in index.html as:
<script src="js/main.js", type="module"></script>
But I get the following error in the browser console.
Uncaught TypeError: Failed to resolve module specifier "lodash".
Relative references must start with either "/", "./", or "../".
Note: I do not wish to use any bundling tool.
If you don't wish to use any bundling tools, you will need to provide a path to the lodash folder within node_modules, relative to the JavaScript file that you have the import statement in.
If you do not wish to use a bundler, it would also be worthwhile importing from the specific file, the function you need. For example:
import _each from '../node_modules/lodash/each'
As of 2021, please consider the following statement by Márton Salomváry (Jan 2018):
Unfortunately even most libraries authored or published in ES6 module format will not work because they target transpilers and rely on the Node.js ecosystem. Why is that a problem? Using bare module paths like import _ from 'lodash' is currently invalid, browsers don’t know what to do with them.
And also the statement by Jake Archibald (May 2017):
"Bare" import specifiers aren't currently supported.
Valid module specifiers must match one of the following:
A full non-relative URL.
Starts with /.
Starts with ./.
Starts with ../.
And javascript.info:
In the browser, import must get either a relative or absolute URL. Modules without any path are called “bare” modules. Such modules are not allowed in import.
Certain environments, like Node.js or bundle tools allow bare modules, without any path, as they have their own ways for finding modules and hooks to fine-tune them. But browsers do not support bare modules yet.
Bundlers facilitate the use of "Bare Imports" which is not supported by the browser yet. Unless you bundle your code, I recommend using the solution proposed by #Asler. Besides, a lot of work is currently being done to study the implementation of "Bare Imports" in the browser, please follow this link if you want to monitor the overall progress.
Eventually you can't use JS modules on browser like that. These modules are for webpack or other bundler.
Try module lodash-es
import each from '../node_modules/lodash-es/each.js'
If you are trying to import css file, make sure to mention .css in import statement.
you can add your node_modules to the public dirs, so you can easily shorten your importing syntax from ../../../../node_modules/my-package into /my-package
also, you need to specify the full path including the file and the extension
import mod from "/my-package/file.mjs"

How to import static url using webpack

How can I import a static url using webpack:
index.js
import 'http://google.com/myscript.js'
It's really unclear what you're trying to do, but in general you have a few options.
Pre-download the script or install it via NPM. This probably is the preferred way to deal with external dependencies. Once it is local you can easily import or require it like any other module.
If it absolutely must be loaded dynamically you will need a 3rd party module such as https://www.npmjs.com/package/scriptjs which can easily download 3rd party modules at runtime and block the execution of the rest of the script until it has been parsed.
Use a <script> tag and include it on your page. This only works if it's a general dependency that can be loaded before everything else (maybe for a polyfill or a library you depend on everywhere like jquery.)
I hope that helps!
This webpack issue says you can use this comment to allow the import to just work. Though this is only dynamic import not static.
import(/* webpackIgnore: true */ "https://example.com");
First seen here https://stackoverflow.com/a/69951351/4619267
import is es6. With es5 and webpack, use require, or better wrap your JS files with AMD/UMD.

Categories