Share JavaScript file resources with another Javascript without using HTML - javascript

I need to use the functions of a javaScript file in another javaScript file, but I do not have an HTML linking the 2, how to share it?
const {Builder} = require('selenium-webdriver')
var chrome = new Builder().forBrowser('firefox').build()
login(chrome);
this is my code main and i need get this other method to other JavaScript File.
function login(chrome, user, senha){
chrome.get('https://testerbeta.crm2.dynamics.com/main.aspx');
}
now the code is small, but the software that I have to test is great and I need to separate the methods in different javascripts files

I think what you're looking for are import and export, added in ES6.
Basically, in the file you want to get your functions from, just add export keyword before function declarement, just like that:
export function foo() {
return bar;
}
Then, in the file you want to inject your function in, you add this at the beginning of the file:
import { foo } from 'path/to/your/file_with_function_to_export.js'
More about that you can read here.

Related

Is it possible to only convert a dart function to javascript

I am currently using the following package where the readme illustrates the following
final bool loaded = await JsIsolatedWorker().importScripts(['test.js']);
I am using the isolate worker package so my code can work on web and outside of web. I would like to generate javascript code from my dart code. I have one file with a top level function and I use
dart compile js -O0 -o test.js test.dart
which I found here
https://dart.dev/tools/dart2js
this is my dart file
void main(List<String> args) {
doComputation('');
}
String doComputation(String input) {
return 'output';
}
I can generate javascript only if I have a main function but this generates a javascript file where the doComutation is not a top level function, so I am not sure if the package can call the function. It looks like it generates an entire program instead of just generating one function.
The generated file is too long to post
So what my question comes down to is this. Is there a way to generate javascript from dart for 1 function with its dependencies included instead of having to generate the entire program? So that I can call this function from dart.
I am not an expert but I also had this problem. Here's what worked for me:
In web_worker.dart:
import 'package:js/js.dart';
main(){
allowInterop(doComputation);
}
#JS('doComputation')
String doComputation(String computationInput) {
// Replace this with your actual computation.
final String computationOutput = "output";
return computationOutput;
}
Compile it using:
$ dart compile js web_worker.dart -o webWorker.js
Manually edit webWorker.js, the JS file generated by the compiler:
Delete this line at the top of the file:
(function dartProgram() {
and the line at the bottom of the file with the corresponding closing brace:
})();
I don't understand what's going on here but I found the Javascript version of the function doComputation() defined in webWorker.js as a property of the object "A".
I defined a wrapper at the top of the file like this:
function doComputation(computationInput) {
return A.doComputation(computationInput)
}
and then I was able to use the file with JsIsolatedWorker like this:
final bool loaded =
await JsIsolatedWorker().importScripts(['../web/webWorker.js']);
if (loaded) {
final String computationResult = await JsIsolatedWorker()
.run(functionName: 'doComputation', arguments: computationInput);
} else {
debugPrint('Web worker is not available');
}
If someone who understands this better can elaborate or improve on this solution, that would be great. I don't really have any idea what I'm doing. I'm just posting this to hopefully help other people save time in the future by sharing what worked for me.
You can use js package to call JavaScript APIs from Dart code, or vice versa. To make a Dart function callable from JavaScript by name, use a setter annotated with #JS().
#JS()
library callable_function;
import 'package:js/js.dart';
/// Allows assigning a function to be callable from `window.functionName()`
#JS('functionName')
external set _functionName(void Function() f);
/// Allows calling the assigned function from Dart as well.
#JS()
external void functionName();
void _someDartFunction() {
print('Hello from Dart!');
}
void main() {
_functionName = allowInterop(_someDartFunction);
}
JavaScript code may now call functionName() or window.functionName().
Check google chartjs https://github.com/google/chartjs.dart/tree/master/example for a complete example.
From dart2js "Helping dart2js generate better code" there is a tip :
Don’t worry about the size of your app’s included libraries. The dart2js compiler performs tree shaking to omit unused classes, functions, methods, and so on. Just import the libraries you need, and let dart2js get rid of what you don’t need.
Related to this post https://stackoverflow.com/a/21124252/3733730.
You can do this instead by using the package dart2js
one make a program for your main.dart dart2js where the function or command you wanted to make is there, then create a separate dart file what function you wanted to call, and it will fix your problem, it is a separate file but will only execute one function that you needed to do so and that is the separate file

Include files in node.js directly

I know this questions sounds like a duplicate of this question but it isn't.
This questions shows how to include a file that then stores all of its members in an own namespace. But is there a way to include the file, so that the members are in the default namespace?
So I want something like this,
include("abc.js");
testFunc(1, 2, 3);
where testFunc is declared in abc.js
There is a common namespace in node.js that all loaded files has access to, global
In abc.js:
global.testFunc = () => 'bar';
so below will work
require('./abc');
testFunc(1, 2, 3);
However this is not really advised to be used for performance purposes, except for config values for example
First nodejs does not know include, you should use require or import
If you have a module (testModule):
module.exports = {
testFunc: (...args) => {/* ... */}
}
You should be able to import testFunc into the current 'namespace' using
const {testFunc} = require("./testModule.js");

Using 'export' keyword solely for importing into Unit Tests

I'm using Meteor and am writing unit tests for a Collection. I've got Helper methods for the collection in addition to just regular JS functions.
I.e.
Collection.helpers({
helperFn: function () {
return 'foo';
}
});
//And in the same file
function bar() {
return "bar";
}
Then in my tests file I have something like
import { Collection } from '../collections'
//Use Factory or Stub to create test Document
//This then works just fine and I can assert, etc..
testDoc.helperFn
My question is with wanting to test just the regular 'bar' JS function. This isn't a big deal using ES6 classes because then I can just export the whole class and call any function with an instance of it. But with Meteor I'm finding the only way I can access the function is by using the 'export' keyword.
So in my Collection file
export function bar ({ return bar; });
And now in my test file I'd do something like
import { bar } from '../collection'
I'd rather not add an export statement for every time I test a new function. Is there any way around this or is it not a big deal?
I do think that the export/import is the way to go, but to answer the first part of your question: yes, you can fall back to the original scoping of meteor and put these functions in the global scope of meteor as follows:
do not put your files in the imports/ folder, but into another folder in your project, e.g., server/.
defined the functions as:
bar = function() { /* function body */ }
These variables are interpreted by meteor as being global to the project, and hence do not need to be imported before use.
That said, there was a reason meteor introduced the imports/ folder and corresponding export/import paradigm in version 1.3. It avoids polluting the global scope and makes it much easier to see where things are defined.

require exported typescript class in javascript

I'm moving my nodejs project from Javascript to Typescript. It's going to be a slow process, slowly changing things over a few months as i need to tweak stuff.
I've created a typescript class that looks something like this:
// RedisRepository.ts
export class RedisRepository {
public async getDevice(serial: string) : Promise<Device> {
// blah
return device;
}
}
Then in another Javascript file where i need to reference and then call the functions on the above class.
// ExpressApi.js
const repository = require('../Redis/RedisRepository');
async function getRedis(req, res) {
try {
const device = await repository.getDevice('serialnumberxxx');
res.status(200).end(JSON.stringify(device ));
} catch (e) {
logger.error(e);
res.status(500).end();
}
}
however, when it tried to call the function on the repository it says it doesn't exist. Using chrome debugger, i can see that it exists at: repository.RedisRepository.prototype.getDevice. This doesn't seem the correct way to use the function though.
While I appreciate I could just convert ExpressApi.js to Typescript. I'm going to have this problem with many different files. So i need to use it as JavaScript for now. I'll slowly continue to go round the project and change things to Typescript.
As #crashmstr mentioned, you should create a new instance of RedisRepository, then call getDevice method.
If you still want to use
const repository = require('../Redis/RedisRepository');
syntax, you could export default new RedisRepository() from your RedisRepository.ts file.

how can i access this variable outside the file

Basically i have two .js files ,let it is A.js and B.js and i have code like this
A.js
function details(age,address,name){
//some code
//some code
getData(age);
//some code
}
function getData(ag){
return ag;
}
B.js
here how can i access that getData(?) ??? , i don't want to use global variable and i just want to know is it possible in any way or choosing global variable is last option.
Until now, plain JavaScript doesn't provide a built-in namespace management for JS resources.
Recently, import feature appeared.
The import statement is used to import functions, objects, or
primitives which are defined in and exported by an external module,
script, or the like.
But beware :
This feature is only just beginning to be implemented in browsers
natively at this time. It is implemented in many transpilers, such as
the Traceur Compiler, Babel, Rollup, and Webpack.
In A.js, you could export getData() as clients need it :
function details(age,address,name){
//some code
//some code
getData(age);
//some code
}
export function getData(ag){
return ag;
}
and in the client code could import it :
import { getData} from '/modules/A.js';
getData(...);
If you want to keep plain JS fully supported, a classic workaround used by the authors of JS libraries is using a single global variable that holds all public resources that the client needs.
In this way, you reduce the risk to have conflict with other libraries or client resources.
If you can change the code of these files, you could define a single global variable :
var myNameSpace = {
details : function(age,address,name){
//some code
//some code
getData(age);
//some code
},
getData : function getData(ag){
return ag;
}
....
};
And access to the function by prefixing with the single global variable : myNameSpace.
myNameSpace.getData(...);
In your A.js file store the returning data that is ag in local/session storage.
You can access this data in B.js which will be in local/session storage.
localStorage.setItem("key", "value");

Categories

Resources