I want add stomp.js file to reactjs project. Where should I add this file? In angular are two options: index.html or angular.json. How about react?
JavaScript code from other project:
function connect() {
//connect to stomp where stomp endpoint is exposed
var socket = new WebSocket("ws://localhost:8080/greeting");
ws = Stomp.over(socket);
ws.connect({}, function(frame) {
ws.subscribe("/user/queue/errors", function(message) {
alert("Error " + message.body);
});
ws.subscribe("/user/queue/reply", function(message) {
showGreeting(message.body);
});
}, function(error) {
alert("STOMP error " + error);
});
}
Current project structure:
1 - install the library (using npm or yarn)
2 - import them in any file you need
There is no need to define them in a central namespace or something (indeed package.json will act like that);
for example stomp.js:
1 - npm i #stomp/stompjs
2 - now using it's Client in app.js
import { Client } from "#stomp/stompjs";
function App() {
const stompClient = new Client({});
return (
<main>
</main>
);
}
You can add external js files through the import keyword in ES6. Basically you should do:
import exportedFunction from "<path-to-file>/stomp"
This should work, assuming that "stomp.js" is a file in your project structure and not a package to be installed (in this case you should install it using the package manager first before importing)
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Related
I am trying add a qr code scanning functionality to my react app. I am using #zxing(https://www.npmjs.com/package/#zxing/browser & https://www.npmjs.com/package/#zxing/library) packages.
Following the readme, here's my js code. I have hosted the application on aws so its SSL covered. But I can't seem to figure out the issue. I have read the git repo of both and the functions do exists(https://github.com/zxing-js/browser/tree/master/src/readers)
import React, { useState, useEffect } from "react";
import {
NotFoundException,
ChecksumException,
FormatException
} from "#zxing/library";
import { BrowserQRCodeReader, BrowserCodeReader } from '#zxing/browser';
export default function() {
var qrCodeReader = null;
var codeReader = null;
var sourceSelect = null;
console.log("ZXing code reader initialized");
useEffect(() => {
codeReader = new BrowserCodeReader();
qrCodeReader = new BrowserQRCodeReader();
console.log(codeReader.listVideoInputDevices()); // ISSUE: RETURNS -> listVideoInputDevices() is not a fuction
console.log(qrCodeReader.listVideoInputDevices()); // ISSUE: RETURNS -> listVideoInputDevices() is not a fuction
console.log("Code Reader", codeReader); // ISSUE: SEE IMAGE BELOW
console.log("QR Code Reader", qrCodeReader); // ISSUE: SEE IMAGE BELOW
}, []);
Instead of using the import try using:
`
const zxing = require('zxing-js/library');
`
I am currently stuck with a problem trying to fetch github repo data using the octokit npm package.
I use vite to run a dev server and when I try to make a request, the error that i get is:
Uncaught Error: Module "stream" has been externalized for browser compatibility and cannot be accessed in client code.
My React .tsx file looks like this:
import { Octokit, App } from 'octokit'
import React from 'react'
const key = import.meta.env.GITHUB_KEY
const octokit = new Octokit({
auth: key
})
await octokit.request('GET /repos/{owner}/{repo}', {
owner: 'OWNER',
repo: 'REPO'
})
export default function Repos() {
return (
<>
</>
)
}
I have redacted the information for privacy purposes.
If anyone knows how to resolve this issue with vite, please let me know!
Check first if this is similar to octokit/octokit.js issue 2126
I worked around this problem by aliasing node-fetch to isomorphic-fetch. No idea if it works for all usages within octokit, but works fine for my project.
You'll need to install the isomorphic-fetch dependency before making this config change.
// svelte.config.js
const config = { // ... kit: {
// ...
vite: {
resolve: {
alias: {
'node-fetch': 'isomorphic-fetch',
},
},
},
},
};
export default config;
Note: there are still questions about the support/development of octokit: issue 620.
I want to use web workers in my app.
This is my worker:
import { processOrderFieldValue } from './utils';
export function colsAndRowsWorker() {
this.onmessage = () => {
processOrderFieldValue();
// in this place the compiler is trying to convert this module to this:
//Object(_WEBPACK_IMPORTED_MODULE_0__["processOrderFieldValue"])
//and I've got this:
//Uncaught ReferenceError: _WEBPACK_IMPORTED_MODULE_0__ is not defined
postMessage('oops');
};
}
I also tried to use importScripts('./utils'), but also got an error.
How to use modules in worker inside the React app? Perhaps, I can define the function as a relative path in importScripts()?
I'm trying to use qrcode-generator in my app but no success with my settings even though it's working in plunker, in my app I'm using angular-cli and angular 2.rc-1.
Steps to reproduce:
ng new newAppName
cd newAppName
ng serve
it works, then.
npm i qrcode-generator // (note this is missing the svg support).
ng serve // still work
then change the configurations in 2 files.
angular-cli-build.js:
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
'systemjs/dist/system-polyfills.js',
'systemjs/dist/system.src.js',
'zone.js/dist/**/*.+(js|js.map)',
'es6-shim/es6-shim.js',
'reflect-metadata/**/*.+(js|js.map)',
'rxjs/**/*.+(js|js.map)',
'qrcode-generator/**/*.+(js|js.map)',
'#angular/**/*.+(js|js.map)'
]
});
};
and system-config.ts:
/**********************************************************************************
* User Configuration.
*********************************************************************************/
/** Map relative paths to URLs. */
const map: any = {
'qrcode-generator': 'vendor/qrcode-generator'
};
const packages: any = {
'vendor/qrcode-generator': {
main: 'qrcode',
defaultExtension: 'js'
}
};
// ... the rest is the same
edit new-app-name.component.ts and import the qrcode-geenerator in it like this
// vscode underline the qrcode-generator string and complai about not finding it
import * as qrcode from 'qrcode-generator';
then ng serve which is still running errors out with this message:
/path/to/project/newAppName/tmp/broccoli_type_script_compiler-input_base_path-jscpZEq5.tmp/0/src/app/new-app-name.component.ts
(3, 25): Cannot find module 'qrcode-generator'.
I tried installing the typings for it by adding this to the typings.json file:
"globalDependencies": {
"qrcode-generator": "registry:dt/qrcode-generator#0.0.0+20160412152159"
}
then running:
typings i
install successful, but still the same error.
angular-cli version:
angular-cli: 1.0.0-beta.5
node: 6.2.0
os: linux x64
Am I missing something?
Is there other configuration I'm missing?
I was able to import this finally thanks to #JavascriptMick from angular-cli's gitter I did the following, first make the format global:
'vendor/qrcode-generator': {
format: 'global',
main: 'qrcode.js'
}
then when importing do it this way:
import 'qrcode-generator';
declare let qrcode;
Hope this help.
I am not sure about the specific requirements you have, but here is an AngularJS (Version 1) app that features a QR-Code generator:
http://quir.li/qr.html
You can
enter the text
select the error code level
select a size
View/Copy/download the QR code from the screen
I am the author of said page, but the QR generator is jsqrencode by tz#execpc.com
My source code is at https://github.com/suterma/quirli/blob/master/website/qr.html
I have
import fs from 'fs'
and in my package.json I have
Then I run the command
> npm i fs
> fs#0.0.2 node_modules/fs
next in my React store I import 'fs' module
import fs from 'fs'
However when I try to use fs
I don't see methods except for constructor and a few other __methods. I don't see the method createReadStream or any other file manipulation methods.
Does anybody know what is wrong? (using Webpack) and can give more information upon request, but I am getting this far...
ps: why is it that I can npm i fs --save when I read on other posts that I do not have to do that (using node 5.5.0)
import Reflux from 'reflux'
import AddItemActions from '../actions/AddItemActions'
import request from 'superagent-bluebird-promise'
import fs from 'fs'
var ImageStore = Reflux.createStore({
init(){
.
.
.
},
decryptImage(file) {
var reader = new FileReader();
var info = {}
reader.onload = (output) => {
debugger
request.post("https://camfind.p.mashape.com/image_requests")
.set("X-Mashape-Key", "KEY")
.set("Content-Type", "application/x-www-form-urlencoded")
.set("Accept", "application/json")
.send({'focus': { 'x': 480}})
.send({'focus': { 'y': 640}})
.send({'image_request': {'altitude': 27.912109375}})
.send({'image_request': {'language': "en"}})
.send({'image_request': {'latitude': 35.8714220766008}})
.send({'image_request': {'locale' : "en_US"}})
.send({'image_request': {'longitude': 14.3583203002251}})
.send({'image_request': {'image': fs.createReadStream("/path" + 'file.jpg')}})
.then(function (result) {
console.log(result.status, result.headers, result.body);
this.info = result
},
function(error) {
console.log(error);
})
}
reader.readAsDataURL(file);
return info
},
.
.
.
.
})
In create-react-app they have stubbed out 'fs'. You cannot import it.
They did this because fs is a node core module.
You'll have to find another solution to that problem. See this ticket.
It's possible this might be an environment issue. It's not possible for the browser to interpret and run some Node server-side modules like fs.
The solution is to run the fs methods in a Node environment (server-side) or to find a package which offers the same functionality but written for the browser.
It's discussed in this question...
Module not found: Error: Cannot resolve module 'fs'
And this question...
Use fs module in React.js,node.js, webpack, babel,express
npm i babel-plugin-preval
Though browser does not allow accessing file system during runtime, You can use prevail in React to read content from file system into memory during build time
like so
// loading content of text file into react project during build time.
// which means everytime text content is changed, you need to rebuild the project to get the updated content.
const greetingContent = preval`
const fs = require('fs')
module.exports = fs.readFileSync(require.resolve('./greeting.txt'), 'utf8')
`
console.log(greetingContent);