Svelte/ Rollup Error “missing global variable name” - amazon-cognito

When I am importing "AmazonCognitoIdentity" in my Routify project I am getting "missing global variable name" error.
Error message:
bundles src/main.js  dist\build\bundle.js...
LiveReload enabled
(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
/js/amazon-cognito-identity.min.js (imported by src\pages\_components\Login.svelte)
(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
/js/amazon-cognito-identity.min.js (guessing 'amazonCognitoIdentity_min_js')
created dist\build\bundle.js in 2.7s
bundles src/sw.js  dist\sw.js...
created dist\sw.js in 1.6s
Following is my code
import { AmazonCognitoIdentity } from "/js/amazon-cognito-identity.min.js";
const authenticationData = {
Username: userName,
Password: password,
};
const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(
authenticationData
);
console.log(authenticationDetails);
const poolData = {
UserPoolId: "xxxx”
ClientId: "xxxxxxx",
};
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
const userData = {
Username: userName,
Pool: userPool,
};
console.log(userData);
const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
const accessToken = result.getAccessToken().getJwtToken();
console.log(`on sucess: ${accessToken}`);
},
onFailure: function (err) {
console.log(`onfailure: ${err}`);
console.log(err);
},
});
and also I’ve linked the following file in _index.html
<script src="./js/amazon-cognito-identity.min.js"></script>
<script src="./js/amazon-cognito-auth.min.js"></script>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script>
And the same process in working good in normal Html ad JavaScript files.

npm i amazon-cognito-identity-js
run this command first then update your import to this:
import { AmazonCognitoIdentity } from 'amazon-cognito-identity-js';

Flowing error is thrown after incorporating
npm i amazon-cognito-identity-js
import { AmazonCognitoIdentity } from 'amazon-cognito-identity-js';
ERROR:
(!) Plugin node-resolve: preferring built-in module 'buffer' over local alternative at 'E:\ec-website\htx-pp-client\node_modules\buffer\index.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
buffer (imported by node_modules\amazon-cognito-identity-js\es\AuthenticationHelper.js, node_modules\amazon-cognito-identity-js\es\CognitoUser.js, node_modules\amazon-cognito-identity-js\es\CognitoJwtToken.js)
[!] Error: 'AmazonCognitoIdentity' is not exported by node_modules\amazon-cognito-identity-js\es\index.js, imported by src\pages_components\Login.svelte
After adding this line to rollup.config.js
rollup.external = ["AmazonCognitoIdentity", "amazon-cognito-identity-js"];
rollup.output = {
file: "dist/build/bundle.js",
format: "umd",
interop: "esModule",
globals: {
"amazon-cognito-identity-js": "AmazonCognitoIdentity",
},
};
The above error is gone. But at run time throws a new error
Uncaught TypeError: Cannot read property 'AmazonCognitoIdentity' of undefined

I got past this error by adding
import polyfills from "rollup-plugin-node-polyfills";
...
plugins: [
polyfills(),
...
to my rollup.config.js

My guess is, you need to change the import statement so that it is relative:
import { AmazonCognitoIdentity } from "./js/amazon-cognito-identity.min.js";
I don't know where this file is, but you need to have . or .. at the start of the location.
As I'm not an expert I yet cannot explain you why.

import AmazonCognitoIdentity from 'amazon-cognito-identity-js';
Is your import correct?

Related

WebSQL threw an error [Error: Error code 1: no such table: document-store]

We are using react-naive-sqlite-2 in our application with RxDB and started getting this error somewhat sporadically. It seems to happen after we remove the database. I was surprised to see this was a WebSQL error since we are using react-native and WebSQL is deprecated. I don't have great ways to debug this but my hunch is that we have some code that still tries to access the now dead database.
This is the code we use to set up our database:
import SQLiteAdapterFactory from 'pouchdb-adapter-react-native-sqlite'
import SQLite from 'react-native-sqlite-2'
import { addRxPlugin, createRxDatabase } from 'rxdb'
import { RxDBReplicationGraphQLPlugin } from 'rxdb/plugins/replication-graphql'
import type { DatabaseType } from '../generated'
/**
* SQLITE SETUP
*/
const SQLiteAdapter = SQLiteAdapterFactory(SQLite)
addRxPlugin(SQLiteAdapter)
addRxPlugin(require('pouchdb-adapter-http'))
/**
* Other plugins
*/
addRxPlugin(RxDBReplicationGraphQLPlugin)
export const getRxDB = async () => {
return await createRxDatabase<DatabaseType>({
name: 'gatherdatabase',
adapter: 'react-native-sqlite', // the name of your adapter
multiInstance: false,
})
The issue happens after we logout and attempt to log back in. When we logout, we call removeRxDatabase. Has anyone ran into this kind of issue before or know of ways to debug?
For posterity, the issue was that we had a reference to the database in our state management library (Zustand) that was being held onto past logout. When we tried to login again, our getOrCreateDatabase function didn't make a new one but it wasn't valid since we had run database.remove() in rxdb. We ended up just clearing the Zustand db and calling database.remove() at one place.
export const useRxDB = create<UseRxDBType>((set, get) => ({
database: undefined,
/**
* we set the database to ready in the LocalDocument store once local docs are loaded into the store
*/
databaseIsReady: false,
getOrCreateDatabase: async () => {
let database = get().database
if (!database) {
database = await createRxDatabase()
if (!Rx.isRxDatabase(database)) throw new Error(`database isnt a valid RxDB database.`)
set({ database })
}
return database
},
resetDatabase: async () => {
const database = get().database
if (database) {
await database.remove()
set({ database: undefined })
}
},
}))

Using bootstrap-tour with Aurelia

I have not been able to find a good example of how to use Bootstrap Tour with Aurelia. I installed it with yarn (yarn add bootstrap-tour) and added the dependencies in main.js as follows:
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-tour/build/css/bootstrap-tour.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';
import 'bootstrap-tour/build/js/bootstrap-tour.min.js';
Now I would like to use it in one of my view-models. Here is what I've tried:
import { Tour } from 'bootstrap-tour';
In my class definition:
#inject(Store, EventAggregator, I18N, Router, Tour)
export default class {
constructor(store, events, i18n, router, tour) {
this.store = store;
this.events = events;
this.i18n = i18n;
this.router = router;
this.tour = tour;
}
// ... other methods and code
startTour() {
const tourNewReports = new this.tour({
steps: [
{
element: '#tour-btn-menu',
title: 'New reports!',
content: 'Check out new reports!',
},
{
element: '.tour-label-product',
title: 'Product report',
content: 'Click on a specific product to see more reports.',
},
],
});
tourNewReports.init();
tourNewReports.start();
}
}
However, this doesn't even compile and I get the following error:
Error: Error invoking _class3. Check the inner error for details.
------------------------------------------------
Inner Error:
Message: key/value cannot be null or undefined. Are you trying to inject/register something that doesn't exist with DI?
Inner Error Stack:
Error: key/value cannot be null or undefined. Are you trying to inject/register something that doesn't exist with DI?
I've also tried skipping the injection and just using const tourNewReports = new Tour({, but I get this error:
bootstrap_tour__WEBPACK_IMPORTED_MODULE_6__.Tour is not a constructor
at _class3.startTour
What am I doing wrong?
The comments from Cristián Ormazábal, avrahamcool and Rabah G helped me with this issue. The simplest solution was:
import Tour from 'bootstrap-tour';
Then, use it directly as follows:
startTour() {
const tourNewReports = new Tour({
steps: [
{
element: '#tour-btn-menu',
title: 'New reports!',
content: 'Check out new reports!',
},
{
element: '.tour-label-product',
title: 'Product report',
content: 'Click on a specific product to see more reports.',
},
],
});
tourNewReports.init();
tourNewReports.start();
}
However, in the end, it appears that bootstrap-tour may be an abandoned repo. It's currently incompatible with Bootstrap 3.4.1 (the latest v3 release), and therefore useless to me. If someone still wants to use it, there are a couple workarounds and an alternate forked repo posted here:
https://github.com/sorich87/bootstrap-tour/issues/723

Vue Storybook Jest Addon configuration problem

I wonder if someone using the jest addon can share it's Vue Storybook configuration, since I can't seem to make it work. I've tried the global mode:
In Storybook's config.js:
import { withTests } from '#storybook/addon-jest';
import results from '../.jest-test-results.json';
addDecorator(
withTests({
results,
})
);
And inside my Story:
storiesOf('Elements/Tag', module)
.addParameters({ jest: ['ThuleTag'] })
.addDecorator(VueInfoAddon)
.addDecorator(withTests({ results })('ThuleTag'))
.add('Squared',
withNotes(_notes)(() => ({
components: {ThuleTag},
template: _template,
propsDescription: {
size: 'medium / small / mini',
type: 'success / info/warning / danger'
}
})),
)
I get this error:
TypeError: Object(...)(...).addParameters is not a function
I've also tried the local way:
In my Story:
import { storiesOf } from '#storybook/vue'
import { withNotes } from '#storybook/addon-notes'
import results from '../../../jest-test-results.json'
import { withTests } from '#storybook/addon-jest'
import ThuleTag from '../../components/ui/elements/ThuleTag.vue'
let _notes = `A simple wrapper for the Elements el-tag, that accepts the same <i>type</i> and <i>size</i> props`
let _template = `<thule-tag
size="small"
key="name">Tag Namez
</thule-tag>`
storiesOf('Elements/Tag', module)
.addDecorator(withTests({ results }))
.add('Squared',
withNotes(_notes)(() => ({
components: {ThuleTag},
template: _template,
propsDescription: {
size: 'medium / small / mini',
type: 'success / info/warning / danger'
}
})),
{
jest: ['ThuleTag.test.js'],
}
)
Here I get this error:
Error in render: "TypeError: Cannot read property '__esModule' of undefined"
And the Tests tab is shown with this message:
This story has tests configured, but no file was found
Can someone point me what's messing things up please?
It looks like storybook jest addon is not supported for Vue.js for now
https://github.com/storybooks/storybook/blob/master/ADDONS_SUPPORT.md
Ok, about first error
Error in render: "TypeError: Cannot read property '__esModule' of undefined"
I think that you should check your babel-config, It seems like you forget some presets for your framework.
About second question
This story has tests configured, but no file was found
That problem happens from Jest and storybook/addon-jest want to get with equals api, but they can't. In last versions of Jest, output file structure has options.testResults , but storybook/addon-jest wants options.results & options.results.testResults.
There are two possible solutions:
use appropriate version of Jest and storybook/addon-jest
apply huck in index.js of storybook-jest library, smth like that
if (testFiles && !testFiles.disable) {
//todo: HERE should be your storybook hack
options.results = options.tests.testResults;
options.results.testResults = options.results;
emitAddTests({
kind: kind,
story: story,
testFiles: testFiles,
options: options
});
}

Circular dependency issue while exporting from single file using babel-module-resolver

I was working on a react native project and while perfoming hot reloading app goes into cyclic recursion resulting in maximum call stack exceeded. More details of this issue can be found here
From here I realised that there is something wrong and circular dependencies are getting created.
I decided to give madge a try and see whats going on in the project. After running the command I saw quite a number of circular dependencies.
Now since my project is quite huge debugging that was quite a task so I created a small version of my project containing a single folder.
I created a utils folder in which I have 4 files: -
utils/index.js
utils/device-helper.js
utils/init.js
index.js
For imports I am using babel-module-resolver
utils/init.js
import {deviceInfo} from "utils";
export const init = () => {
// initialising app and calling backend API with device info
};
utils/device-helper.js
import DeviceInfo from "react-native-device-info";
const API_LEVEL = "v0";
export const deviceInfo = () => {
try {
return Object.assign({}, {
apiLevel: API_LEVEL,
deviceId: DeviceInfo.getUniqueID(),
device: DeviceInfo.getDeviceName(),
model: DeviceInfo.getModel(),
osVersion: DeviceInfo.getSystemVersion(),
product: DeviceInfo.getBrand(),
country: DeviceInfo.getDeviceCountry(),
appVersion: DeviceInfo.getVersion(),
manufacturer: DeviceInfo.getManufacturer(),
userAgent: DeviceInfo.getUserAgent(),
buildNumber: DeviceInfo.getBuildNumber(),
bundleId: DeviceInfo.getBundleId()
});
} catch (e) {
// TODO: Report to Bugsnag
return {};
}
};
utils/index.js
export * from "./init";
export * from "./device-info-helper";
index.js
export * from "./utils";
After running madge command I get following :-
tests-MBP:madge-test harkirat$ madge --circular index.js
Processed 4 files (684ms)
✖ Found 1 circular dependency!
1) utils/index.js > utils/init.js
However, if i change utils/init.js to following it works:-
utils/init.js
import {deviceInfo} from "./device-helpers";
export const init = () => {
// initialising app and calling backend API with device info
};
I am not able to understand the cause of this circular dependency. Can someone please help?
Here is link to the repository.
I don't see a .babelrc in the repo, but here is what I think:
In utils/init.js you import using:
import {deviceInfo} from "utils";
That is same as:
import {deviceInfo} from "./utils/index";
In utils/index.js you do a export * from "./init". This export from basically first imports all the contents of ./utils/init and the reexports it.
So:
utils/init.js imports from ./utils/index
./utils/index.js imports from ./utils/init
There is your circular dependency.

Tests are failing after Angular 2 RC5

I had used the following format for my tests:
export function main() {
describe('Angular2 component test', function() {
it('should initialize component',
async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
var template = '<specific-component-tag>';
return tcb.overrideTemplate(TestComponent, template)
.createAsync(TestComponent)
.then((fixture) => {
expect(fixture.componentInstance.viewChild).toBeDefined();
fixture.detectChanges();
expect(fixture.componentInstance.viewChild.items.length).toBe(1);
// .... etc.
}).catch (reason => {
console.log(reason);
return Promise.reject(reason);
});
})));
});
}
This work fine in RC4. But RC5 came suddenly and now this code have not worked.
It throws me the following errors:
Module ".... #angular/core/testing" has no exported member 'it'.
Module ".... #angular/core/testing" has no exported member 'describe'.
Module ".... #angular/core/testing" has no exported member 'expect'.
Module ".... #angular/core/testing" has no exported member 'beforeEachProviders'.
Module ".... #angular/compiler/testing" has no exported member 'TestComponentBuilder'.
Module ".... #angular/compiler/testing" has no exported member 'ComponentFixture'.
Please help me to migrate this test to angular2 RC5.
Update:
I have already read RC5 release notes but nothing comes to my mind how to achieve my goal.
The Jasmine imports available through #angular/core/testing are removed. So remove the imports for the following
Before:
import {
beforeEach,
beforeEachProviders,
describe,
expect,
it,
inject,
} from '#angular/core/testing';
after
/// <reference path="../../../typings/main/ambient/jasmine/index.d.ts" />
import {
inject, addProviders
} from '#angular/core/testing';
The reference path should be the first line in the file and it should point to jasmine type definition file. (Update the relative up. i.e the ../../ to whatever)To get jasmine type defitions, add the following line to ambientDevDependencies. Mine looks something like this
{
"ambientDevDependencies": {
"angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459",
"jasmine": "registry:dt/jasmine#2.2.0+20160412134438",
"selenium-webdriver": "registry:dt/selenium-webdriver#2.44.0+20160317120654"
},
"ambientDependencies": {
"es6-shim": "registry:dt/es6-shim#0.31.2+20160317120654"
}
}
Also change
beforeEachProviders(() => [InMemoryDataService]);
to
import { TestBed } from '#angular/core/testing';
...
describe('...', () => {
TestBed.configureTestingModule({
providers: [ InMemoryDataService ]
});
it(...);
});
Take a look at changelog:
https://github.com/angular/angular/blob/master/CHANGELOG.md
It looks like API, which you are using is deprecated - path and names has changed. :)
For example:
TestComponentBuilder and ComponentFixture is now in #angular/core/testing,
beforeEachProviders:
code:
beforeEachProviders(() => [MyService]);
changed to:
beforeEach(() => {
addProviders([MyService]);
});
If you already read their release note. It's a lot of change in testing API package.
https://github.com/angular/angular/blob/master/CHANGELOG.md#breaking-changes
So, I didn't try to migrate test to RC5 yet. But I found link about change to new testing API.
https://ng2-info.github.io/2016/08/angular-2-rc-5/#テスティングapiに関する変更
Hope this help.