I have a UMD library and the following works in commonjs...
global.window = global;
var DoSomething = require("../dist/sce-umd.js").DoSomething;
(function(){
var instance = new DoSomething();
instance.doSomethingElse();
})()
I am trying to do the same thing with ESM like...
(()=>{
// Needed for UMD
global.window = global;
import("../dist/sce-umd.js").then((OtherThing)=>{
console.log("This is the next level");
const other = new OtherThing();
other.doSomethingElse();
});
})();
But I get...
TypeError: OtherThing is not a constructor
I also tried new OtherThing.DoSomething() but I get...
TypeError: OtherThing.DoSomething is not a constructor
You must use the .default prop of the returned module, like so below:
import("./some-umd.js").then((myModule)=>{
const myThing = myModule.default; <---- This is the key
// ... do what you need with myThing
});
In normal import, you do the following if import { default as myThing } from './some-umd.js'; doesn't work:
import myModule from './some-umd.js';
const myThing = myModule.default;
Related
I have been using svg-pan-zoom library successfully with my javascript app but I now need to refactor it to use requireJS.
My util.js is:
define([
'baja!',
'jquery',
'/file/WebWidgets/js/libraries/svg-pan-zoom.js'
], function (
baja,
$,
svgPanZoom) {
'use strict';
const updateInitializeDiv = () => {
const svgDocument = $('#svgObjectElementFromBinding')[0].contentDocument;
const svgDocumentElement = svgDocument.documentElement;
console.log(svgDocumentElement);
console.log(svgDocumentElement.tagName);//svg
let panZoomSVG = svgPanZoom(svgDocumentElement, {
zoomEnabled: true,
controlIconsEnabled: true
});
}
const util = {};
util.updateInitializeDiv = updateInitializeDiv;
return util;
});
I am getting "Uncaught TypeError: svgPanZoom is not a function".
Can anyone suggest what I am doing wrong?
I had to reference the svg-pan-zoom library in the RequireJS config to get this to work.
When I use the wrap function from firebase-functions-test I got this error message
Error Message
TypeError: Cannot read properties of undefined (reading 'length')
at isV2CloudFunction (node_modules/firebase-functions-test/lib/main.js:49:26)
at wrap (node_modules/firebase-functions-test/lib/main.js:32:9)
Test file code
const firebaseFunctionsTest = require("firebase-functions-test");
const {wrap} = firebaseFunctionsTest()
describe('Firestore Function Test', ()=>{
let wrappedFunction = wrap(firestoreFunction.firestoreFunction)
beforeEach(()=>{
wrappedFunction()
})
})
Function file code
exports.firestoreFunction = functions.firestore.document('/collection/doc').onCreate(
async(snap, context)=>{
//function logic
});
function functionA(){
//function A logic
}
function functionB(){
//function B logic
}
module.exports = {
functionA,
functionB
}
In the file function, I have used two methods of export,
so in the test file when I call firestoreFunction.firestoreFunction
it will be undefined.
Changing the function file has solved it.
const firestoreFunction = functions.firestore.document('/collection/doc').onCreate(
async(snap, context)=>{
//function logic
});
function functionA(){
//function A logic
}
function functionB(){
//function B logic
}
module.exports = {
firestoreFunction,
functionA,
functionB
}
Issue:
I am using react-intl and I would like to load the language-related JSON file only when it is needed, in brief to lazy load it.
Documentation :
https://reactjs.org/docs/code-splitting.html
the problem here is I wish to lazy load a JSON file not a component, so I am a bit lost about how to use it without JSX.
Actual code :
import React from 'react';
import {IntlProvider} from 'react-intl';
import English from "../i18n/en.json";
import Polish from "../i18n/pl.json";
const local = navigator.language;
let lang;
switch (local){
case "pl":
case "pl-pl":
lang = Polish;
break;
default:
lang = English;
}
function Wrapper () {
[...]
}
export default Wrapper
What I try which did not works :
test 1:
import React from 'react';
import {IntlProvider} from 'react-intl';
const English = React.lazy(() => import('../i18n/en.json'));
const Polish = React.lazy(() => import('../i18n/pl.json'));
const local = navigator.language;
let lang;
switch (local){
case "pl":
case "pl-pl":
lang = Polish;
break;
default:
lang = English;
}
function Wrapper () {
[...]
}
export default Wrapper
test 2:
import React from 'react';
import {IntlProvider} from 'react-intl';
const English = React.lazy(() => import('../i18n/en.json'));
const Polish = React.lazy(() => import('../i18n/pl.json'));
const local = navigator.language;
let lang;
switch (local){
case "pl":
case "pl-pl":
Polish.then(polish => {lang = polish});
break;
default:
English.then(english=> {lang = english});
}
function Wrapper () {
[...]
}
export default Wrapper
test 3 (inspired from How to import Json file with React lazy loading?) :
import React from 'react';
import {IntlProvider} from 'react-intl';
const local = navigator.language;
let lang;
switch (local){
case "pl":
case "pl-pl":
import("../i18n/pl.json").then(Polish=> {
lang = Polish);
});
break;
default:
import("../i18n/en.json").then(English=> {
lang = English);
});
}
function Wrapper () {
[...]
}
export default Wrapper
In case more code is needed (the function Wrapper for example), please let me know in a comment :)
I also had the same issue where I wanted to code split my JSON in React. I found a work around that uses the dynamic import function.
I wasn't using Intl so I can't confirm this works for your needs but this is what worked for my needs (and I think it should work for you)
I created a function to return a promise with my data that I needed to code split. I then called this in my Component in an Async func with an await on the data.
My use case was to fetch data from an API, if that was done, load a cached JSON of the data.
const loadCached = (key) => {
return new Promise((res, rej) => {
import(`../datasets/cached/${key}.json`).then((data) => {
res(data?.default);
});
});
};
I then called it from my async catch
const cachedData = await loadCached(key);
So for you use I would keep my loadCached function (maybe rename it to like loadLang)
then wrap it in a useEffect to fire on load to change the language and gather the JSON.
Here is how I would approach your issue (untested code)
const local = navigator.language; // get language
const [lang, setLang] = useState("English"); // for a default of english
// fire when we get local from DOM
useEffect(() => {
async function getLangData() {
const response = await loadLang(local);
setLang(reponse);
}
getLangData();
}, [local])
const setLang = (lang) => {
return new Promise((res, rej) => {
import(`../i18n/${lang}.json`).then((data) => {
res(data?.default);
});
});
};
Here I am using some method for frequently used methods in common method ts file. If I am going to access these method I got null values Please help me out.
CommonMethod.ts:
GetCategoryList(){
let Mylist = [];
this.auth.Get("Master/Category").then((user) => {
Mylist= user.json();
});
return Mylist;
}
My Another component:
I am trying to access common method ts file here. by below way.
import {CommonMethod} from './CommonMethod';
...
...
construtor(private com:CommonMethod){}
ngOninit(){
console.log(this.com.GetCategoryList());
}
this.auth.Get is going to be async in nature due to which the return MyList line will get called even before the callback to the then method is called and the data is arrived and set in MyList.
You can use the async await syntax to fix it:
async GetCategoryList() {
let Mylist = [];
const user = await this.auth.Get("Master/Category");
Mylist = user.json();
return Mylist;
}
You can then use it like this in your Component:
import {CommonMethod} from './CommonMethod';
...
...
construtor(private com: CommonMethod) {}
async ngOninit() {
const myList = await this.com.GetCategoryList();
console.log(myList);
}
PS: Make sure that CommonMethod is a service and is added to the providers array of your #NgModule
Should update your common method:
GetCategoryList(): Promise<any>{
let Mylist = [];
return this.auth.Get("Master/Category").then((user) => {
Mylist= user.json();
Promise.resolve(Mylist);
});
}
And
ngOninit(){
this.com.GetCategoryList().then(results=>{
console.log(results);
});
}
All:
I am pretty new to ES6, when I study ES6 module with this post:
http://www.2ality.com/2014/09/es6-modules-final.html
[1]
there is one line:
export { each as forEach };
I wonder if anyone could tell where can I find the usage intro to this specific syntax (especially the curly bracket and AS )
[2]
Another confuse is about default export:
cmod.js
export default var Obj={};
Obj.hello = function(){
return "hello";
}
main.js
import hello from "./cmod"
console.log(hello.hello());
I wonder why I got error like: :
SyntaxError: cmod.js: Unexpected token (1:15)
> 1 | export default var Obj={};
| ^
But if I move the declaration to a separated line like:
var Obj = {}
export default Obj;
Obj.hello = function(){
return "hello";
}
Then everything works, why I can not declare a variable and export it?
Thanks
[1] export { each as forEach }; this line means, you can export one or more items as objects with or without alias names.
example-1:
const MY_CONST = ...;
function myFunc() {
...
}
export { MY_CONST, myFunc };
example-2:
export { MY_CONST as THE_CONST, myFunc as theFunc };