Importing All Modules in a file and Use them - javascript

I have a lot of modules in my project and I want to import them in a single file. I will transfer the Modules.js file to other files. Example:
modules.js :
const react = require("react")
const reactDOM = require("react-native")
const babel = require("babel")
const jquery = require("./jquery.min.js")
app.js:
const modules = require("./modules.js")
reactDOM.render(<h1>Hello,World</h1>,parentElem)

I found what I want. And now I remember I should answer my own question.
my modules file :
function loadmodule(src) {
elem = document.createElement("script")
elem.src = src
document.head.appendChild(elem)
}
loadmodule(<jquery-file>)
my file :
import {} from "modules.js"
console.log($) //is jquery loaded it returns an object

Related

How can import a global variable into another file?

I am trying to use a global accessToken variable within another file but I keep getting the error Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\Taat\Documents\Backend\server\controllers\authController' imported from C:\Users\Taat\Documents\Backend\server\controllers\dataController.js code: 'ERR_MODULE_NOT_FOUND'
where I am exporting it within authController and importing it within dataController as you can see below in the code:
authController.js:
export let accecssToken;
// rest of my code
dataController.js:
import { accecssToken } from "./authController";
export async function getActivityId(req, res) {
const data = await getDataPromise();
const activityIds = {};
for (let i = 0; i < data.length(); i++) {
activityIds[data[i].id] = [];
}
return res.json(activityIds);
}
export async function getDataPromise() {
const link = `api/?access_token=${accecssToken}`;
console.log("Link = ", link);
const response = await axios.get(link);
return response.data;
}
I do not see what I am doing wrong here can anyone spot it?
Both files are in the same directory as you can see from the error messages paths
Just add extension of exported file
import { accecssToken } from "./authController.js";
or You can use
const { accecssToken } = require('./authController');
Use -
const {accessToken} = require("./authController");
Though seeing the naming convention and your code you're utilizing the accessToken, I would not recommend adding SECERTS in js files as it could be compromised.
Make a .env file at the root folder and add all secrets inside.
.env file should look like -
To use any .env variable, add
require("dotenv").config();
and then use -
const link = `api/?access_token=${process.env.ACCESS_TOKEN}`

How to use an existing JS file in a vue project

I need to use this JS file in my vue3 project.
https://gist.github.com/imolorhe/b31f95e1548ad7d1b233de26267fe21c#file-jungle-js
My JS library is
import { Jungle } from "./jungle.js";
async pitchTransform(
audioBuffer,
pitchMod
) {
let ctx = new OfflineAudioContext(
audioBuffer.numberOfChannels,
audioBuffer.length,
audioBuffer.sampleRate
);
let source = ctx.createBufferSource();
source.buffer = audioBuffer;
let pitchChangeEffect = new Jungle(ctx);
}
The application shows this error:
Uncaught SyntaxError: The requested module '/src/js/jungle.js?t=1659194585032' does not provide an export named 'Jungle' (at voiceTransform.js?t=1659199164108:1:10)
What's the recommend way to include and use jungle.js in this setup?
As the error is saying, that file has no export named "Jungle". In fact it has none.
You have to export that function manually, by editing that file and appending an export keyword:
// ...
export function Jungle(context) {
// ...

How do I resolve the error I have in my JavaScript using imports?

I'm attempting to import a function from 2 different files into another one of my JavaScript files, but in the file that's importing the functions, I'm getting the error that each function is declared, but never read.
capital.js file:
function capital(string) {
const capitalizedString =
string.substring(0, 1).toUpperCase() + string.substring(1);
return capitalizedString;
}
alert(capital("Jon"));
export default capital;
addDOMContent.js file:
function addDOMContent(content) {
const node = document.createElement("h1");
node.innerText = content;
document.body.appendChild(node);
}
addDOMContent("Success!");
export default addDOMContent;
index.js file:
import capital from "./capital.js";
import addDOMContent from "./addDOMContent.js";
Why aren't my files being properly imported?

Issue installing #tensorflow-models/knn-classifier with npm

I installed #tensorflow-models/knn-classifier with npm, but when i run it i get an error "Cannot find module '#tensorflow-models/knn-classifier'".
I can see the module under node modules but still i get this error. Other models like #tensorflow-models/mobilenet, #tensorflow-models/universal-sentence-encoder are resolved but not the knn-classifier. Is there something additional needed for this model?
import * as tf from '#tensorflow/tfjs';
import * as knnClassifier from '#tensorflow-models/knn-classifier';
const classifier = knnClassifier.create();
const trainData = getTrainingData();
for(const td of trainData) {
classifier.addExample(td.xs, td.label);
}
For now the package is missing index.js. Here is the fix
const tf = require('#tensorflow/tfjs');
const knnClassifier = require('./node_modules/#tensorflow-models/knn-classifier/dist/knn-classifier');
const classifier = knnClassifier.create();
console.log('classifier', classifier)

Electron: Load a file with `executeJavaScript`

I need to inject an NPM package into a BrowserView by using executeJavaScript. The package is Web3 and here is what I've tried so far.
import Web3 from 'web3'
const web3 = '' + Web3; // stringify the Web3 class
view.webContents.executeJavaScript(`
const provider = // ... provider got injected successfully because it doesn't have dependencies.
const web3 = new ${web3}(provider);
`)
But this throws the following error.
Uncaught ReferenceError: core is not defined
at new Web3 (<anonymous>:45:5)
at <anonymous>:41:16
Web3 is trying to load its core dependency which unfortunately did not get stringified.
So my question is, how can I load this whole package into the BrowserView? Aka how can you load npm package in the browser, if you do not have control over <script /> tags (at least I wouldn't know how to inject those in Electron)?
Update:
Because of what OJ Kwon suggested in the comments, I tried bundling Web3 with Browserify by running
browserify packages/web3/src/index.js -o web3-bundle.js
. It seemed to have worked, because at the very end of the bundled file (web3-bundle.js) it says:
// ... 50k+ lines long file
var version = require('../package.json').version;
var core = require('web3-core');
var Eth = require('web3-eth');
var Net = require('web3-net');
var Personal = require('web3-eth-personal');
var Shh = require('web3-shh');
var Bzz = require('web3-bzz');
var utils = require('web3-utils');
var Web3 = function Web3() {
var _this = this;
// sets _requestmanager etc
core.packageInit(this, arguments);
this.version = version;
this.utils = utils;
this.eth = new Eth(this);
this.shh = new Shh(this);
this.bzz = new Bzz(this);
// overwrite package setProvider
var setProvider = this.setProvider;
this.setProvider = function (provider, net) {
setProvider.apply(_this, arguments);
this.eth.setProvider(provider, net);
this.shh.setProvider(provider, net);
this.bzz.setProvider(provider);
return true;
};
};
Web3.version = version;
Web3.utils = utils;
Web3.modules = {
Eth: Eth,
Net: Net,
Personal: Personal,
Shh: Shh,
Bzz: Bzz
};
core.addProviders(Web3);
module.exports = Web3;
Now, I'm trying to import and include it like this:
const Web3 = require('./web3-bundle.js');
which doesn't work. It says undefined is not a constructor.
const Web3 = require('./web3-bundle.js').Web3;
and
const Web3 = require('./web3-bundle.js').default;
both didn't work, either. How should one do this?
Update 2:
Inspecting the bundle further, it has uses exports. and module.exports =. My editor only suggests methods and objects exported with exports. as importable 🤔
I suggest you to use this boilerplate or a boilerplate including a good webpack configuration (suggested boilerplate).
Follow these steps:
Clone the repository
Run yarn install
Run yarn add web3
Add import Web3 from 'web3'; into the app/containers/HomePage.js file (react render view).
Enjoy

Categories