vanilla js import and export in old project - javascript

I am trying to clean up the js in an old project, where I cannot add things like typescript etc.
So I am trying to split up the functionality into different files, and create some order from the chaos (I currently have multiple 10k lines js files).
For example I have an index.js which is for a specific page.
On that page I am trying to call a function via an onclick to call dmrLookupByType
import * as dmrService from "../../services/DMRService.js";
// function to be called from HTML
function dmrLookupByType(type){
console.log("called dmrLookupByType function");
dmrService.dmrLookUp(type);
}
In DMRService.js there is a single function (so far)
export function dmrLookUp(type)
{
console.log("reached dmrLookup in DMRService file");
console.log("received type: ", type);
}
The script it self is included on the page as this.
<script type="module" src='/javascripts/src/pages/applicationCreate/index.js'></script>
But i keep getting "Uncaught ReferenceError: dmrLookupByType is not defined"
I also tried wrapping dmrservice in a class to use, but that didn't really change anything either.
Any ideas what I'm doing wrong?

Related

How to Blazor interop call a function from an js script (TS generated) of type module

I hope I didn't miss any appropriate solution from another topic. Like the topic says, I'm using blazor with interop calls. That works fine, but now my TypeScript file with the class definition uses another TS module via import. Later I added the script with the type="module" attribute, to avoid another issue.
Now my interop calls (via JSRuntime) to this script functions doesn't work anymore, probably because of the limited scope of the module classes and variables?
Before the code follows, thanks a lot for your help !
Sample class in CanvasFeeder.ts/js with Method to call via interop:
export class CanvasFeeder
{
public InitCanvas(){ }
}
export * as CanvasFeed from "CanvasFeeder";
var MyCanvasFeeder = new CanvasFeeder();
var ToCallInterop = () => {MyCanvasFeeder.InitCanvas();};
Script reference index.html:
<script src="typescript/CanvasFeeder.js" type="module"></script>
What have I tried?
JSRuntime.InvokeVoidAsync("ToCallInterop");
JSRuntime.InvokeVoidAsync("MyCanvasFeeder.ToCallInterop");
I also tried to instantiate the class and function directly in the index.html.
What are the error message?
Unhandled exception: Could not find 'ToCallInterop'
Unhandled exception: 'ToCallInterop' is not a variable (when instantiating var directly in area of index.html
Blazor looks for functions to call on window, so you would need to store your MyCanvasFeeder object in the window object.
window['MyCanvasFeeder'] = new CanvasFeeder()

How to include plain JavaScript in a React app?

I'm trying to create a React page which includes a p5 sketch, but doing so seems to require me to rewrite standard JavaScript I would normally run in a browser to make it work as a react component.
For example, I'd like to have React serve this code to the client:
function setup() {
createCanvas(600, 600);
}
function draw() {
background(0);
}
But I can't find a way to just have React give the client a JavaScript file. Instead I have to create a component like this:
export default function(p: p5) {
p.setup = function setup() {
p.createCanvas(600, 600);
};
p.draw = function draw() {
p.background(0);
};
}
This might seem trivial but if my team and I can include code that we've already written which works outside of react without having to rewrite everything would make things much easier.
One way to solve the problem is to just place the file in the public directory of React and just serve it statically along with index.html, but I'd prefer to only give the client the file when it needs it instead of just serving every file at once. If I could just have a component import the JavaScript file and send it like it can do with images, that would be exactly what I'm looking for.
Edit: Sorry, to clarify what I meant, Node is what's actually serving things, what I want is when React renders a page it will also run JavaScript code as if it were written in a <script> tag in the HTML page.
I've solved it. Essentially I put all of the code I want to run in a file like sketch.js but surround it in a function which is exported:
export default function Sketch() {
function setup() {
createCanvas(600, 600);
}
function draw() {
background(0);
}
}
Then in app.js you can do something like:
import Sketch from './sketch';
Sketch();
That will run all of the code in that function in the client's browser.
So just an option, we do this for optionally loading certain scripts on our app. In your component on the constructor (or maybe the willMount, play around with it) create a new script tag and append that script tag to the head of you app. This will cause the script to only be run when this component is rendered (Depending on where you called the function to add the script tag). You might also have to think about removing the script tag depending on what your doing, but you get the idea.
The function would look something like this:
addScriptTag = () => {
script = document.createElement('script');
script.src = [url/path of the javascript you want to server from your node server];
// Or just set the javascript on the script tag by adding innerText and type arts
document.head.appendChild(script)
}
then do something like:
constructor() {
this.addScriptTag();
}

Functions included from the prototype in a javascript class are not seen in the editor's autocomplete

I have the following problem, I have created a library. which its methodos
they are in separate files writeLog.js in a folder called ./lib.
and I have an index.js file that explores that folder and extracts the function
and puts the same name as the file as the function name.
example:
writeLog.js
and then I can use
let jsPackTools require('./index');
let utils = new jsPackTools();
utils.writeLog('test');
The way I use to add the methods to the classes is through the prototype.
the folder is scanned with readdirSync () and then I take the file name to
place it inside a require ().
the code is the following:
fs.readdirSync(__dirname+'/lib').forEach(modules => {
let module = modules.split('.').shift();
jsPackTools.prototype[module] =require(\`${__dirname}/lib/${module}\`);
});
Everything works perfectly fine, the problem is that when I want to access my methods through the autocomplete of any code editor. Methods they seem to be not accessible. however everything works perfectly, I can do use of functions.
    
The problem is that I have to know each method that I am going to use and it cannot be visualized in the completed auto of any editor.
I have tried with:
const writeLog = require('./lib/writeLog');
class jsPackTools {
get writeLog() { return writeLog.bind(this) }
}
This allows indexing perfectly. however, I don't logo do it dynamically.
The idea is that the class does not know what its methods are until the ./lib folder is scanned and all methods are extracted. This way you can add functions inderteminately and when you use them you can see.
    
I do not want to use transpilators, I thought of using a d.ts but it is necessary to use typeScript but the intention is to create this library without dependencies or the least possible.

How do I add a personal script to an existing node.js library?

I have a local copy of the hls.js library and I need to include a personal script with custom functions in it.
How do I go about adding a new script to the library and how do I use the function written in the new script?
Let's say that I want to add a script called hello.js that contains a function that logs "Hello World".
When I call that function in my main.js I need it to execute.
Any ideas on how to do this?
Currently, I'm getting an error that the function is not defined.
I placed the hello.js script in the src folder of the library but this (as expected) doesn't seem to work.
It should be possible to add functions to the exported hls.js object.
Your custom-script.js:
var hls = require('hls.js')
hls.customFunc1 = function () {
}
hls.customFunc2 = function () {
}
on main.js:
require('custom-script')
// your code follows
Any other code would be able to use the custom functions by just require'ing hls.js.

meteor / javascript function not working when in another file

This is interesting.
I have a file structure as such:
/
/client/
/server/
The app I'm working on is working fine, I have many .js files in the /client/ folder, all separated into logical (to me) sections. They work fine when compiled.
I have added a new file though, called miscFunctions.js to the mix and added a simple function and saved:
function sessionDataReset(){
//Set the New Organisation Session data to be false, meaning we're not adding a new organisation
return Session.set('addingOrganisation', false);
};
This function, when called returns the following error:
Uncaught ReferenceError: sessionDataReset is not defined
When I move that exact code though to the .js file I'm calling it from it works fine.
Why is the error happening as I was of the understanding what I'm trying to do can be done with Meteor?
Any advice greatly appreciated.
Rob
First try declaring your file this way:
sessionDataReset = function() {
//Set the New Organisation Session data to be false,
//meaning we're not adding a new organisation
return Session.set('addingOrganisation', false);
};
This ensures the function will be visible globally.
(#user1623481 Meteor wraps files as IIFE's when it compiles them, creating a function scope that was limiting the visibility of this function.)
This will most likely resolve it, but following this check the file load order in the Meteor Docs

Categories