How to run several code before import syntax in Javascript? - javascript

I want to run several code before the code inside import syntax gets executed.
Example
file-1.js
console.log('Inside File 1')
import './file-2.js'
file-2.js
console.log('Inside File 2')
Output
Inside File 2
Inside File 1
The output I expected
Inside File 1
Inside File 2
Environment
Node JS v12.19.0 with Module configuration
Real Case
file-1.js
process.env.SHARED_DATA = 'Hello world'
import './file-2.js'
file-2.js
console.log(process.env.SHARED_DATA)
Output
undefined

You can define the env data in separate file. The import syntax will run in the order against the other imports as #loganfsmyth says.
Example
main.js
console.log('Inside main.js file')
import './set-env.js'
import './file.js'
set-env.js
console.log('Inside set-env.js file')
process.env.SHARED_DATA = 'Hello world'
file.js
console.log(process.env.SHARED_DATA)
Output
Inside set-env.js file
Hello world
Inside main.js file

The best way I find is to use top-level await with dynamic import.
process.env.SHARED_DATA = 'Hello world';
await import('../index.js');

In JavaScript the lines don't necesarily wait for the line before to end. One way to solve this issue of yours is to put the file-1.js into a async function:
async function f() {
process.env.SHARED_DATA = "Hello world";
return Promise.resolve(1);
}
f().then(() => {import "./file-2.js"});
By calling this function you can make sure the import waits for the f function to end! Then running the arrow function. Hope this helped if you want to read more about this topic here you go. https://javascript.info/async-await

Related

can i use normal javascript code if in that code imported some module

So in my code it gives me error FunctionOfMainJs is not defined which is function made of main.js so what can i do for run normal js code and also use import in same file
main.js
import {CreateDropDown} from "./asset/js/customdropdown.js";
new CreateDropDown([{"ImagePath":null,"OptionValue":"text1"}],"Container");
function FunctionOfMainJs(){
alert("hey guys");
}
FunctionOfMainJs();
Are you trying to call this function in another .js file? If so you will need to export the function:
module.exports = {FunctionOfMainJS}

Running unit test on JS runtime for es6 import statement

I am very new to NodeJS and JS as well. I have tried reading about resources like babel and rewire which help in resolving dependencies of ES6. But ended up being confused.
I am trying to write unit test for a JS runtime file which has import statements. The issue is that this file is a runtime file. This means that the import module only works when running in browser inside the dependent platform/application.
runtimeFile.js
import {something} from 'other-module'
function foo(){
}
export const toBeTested = {
foo
}
unitTest.js
const toBeTested = require('./runtimeFile').toBeTested
describe('some test', () => {
it('test a func', () => {
const result = tobeTested.foo();
});
});
When i try to run this unit test using mocha getting:
SyntaxError: Unexpected token {
This is for the import statement in runtimeFile.js.
So my question is around:
How do i mock the import statement
I am not sure what configuartion i need to do in order to get rid of this syntax error
I can provide more information as needed

module.exports not working as expected

I would like to export one function in node and call it in another file. Somehow it is always executing the whole code in the exporting module (not only the function exported).
//file: test.js
module.exports = function () {
console.log("Hello");
}
console.log("Hello2");
//file: test2.js
var test = require("./test");
test();
// Desired Output: Hello
// My actual Output: Hello2 Hello
Can somebody please explain, why it is also running the second log (Hello2) although this log is not within the exported brackets?
When you require a file, you import the entire file and it gets executed. Since console.log('Hello2'); isn't defined in a function, it gets executed when the file is required.
This is why you should see Hello2 first. And then you call the test function which executes and prints out Hello.
Your output should be:
Hello2
Hello
Try to do a named export,
for example:
module.exports = function first () {
console.log("Hello");
}
and in your test2.js:
var test = require("./test");
test.first();
When you do var test = require("./test"); you are requiring the whole file, rather than just the module you exported. In the file where you wish to use the function, you need to import the function from the other file.
Try doing this:
//file: test.js
module.exports = function () {
console.log("Hello");
}
console.log("Hello2");
//file: test2.js
import { test } from './test'
test();

Webpack bundling simple JS files

I realize this might prove a total misunderstanding of what Webpack is for but I've not been able to find a straight answer anywhere.
Basically I have two files:
hello.js
function hello() {
console.log('Hello, world!');
}
entry.js
require('./hello.js');
hello(); // should log 'Hello, world!'
I wanted to pack them into a single file for faster loading using Webpack. My condition was that I should not have to modify hello.js in any way (let's say it is a big, obfuscated library that I don't have the right to modify).
I expected that running
webpack entry.js result.js
will give me a usable bundle in result.js but instead result.js gives me this error:
Uncaught ReferenceError: hello is not defined
Is there a way to achieve what I want? Just simply bundle scripts together to make them available in the global namespace without having to add anything to them ?
File hello.js is not exporting anything, you have to export hello function from hello.js file like this,
module.exports = function () {
console.log('Hello, world!');
}
and then in your entry file.
var hello = require('./hello.js');
hello();

Writing a script file to test a function? (Node.js)

I'm currently working on a program where I have a function that runs and does a bunch of things. I wrote a script over the summer at work that could take dummy input and pass it to a function call and then all I had to do was open a command prompt and say node test.js.
Unfortunately I don't remember what that code looked like exactly but I know it was fairly simple.
For simplicity's sake, lets say I have a function:
var double_num = function(num){
return num*2;
}
contained in a file called double.js
and I also have a blank javascript file test.js. How complicated is it to call double_num from test.js with something in the file like:
var result = double_num(5);
console.log(result);
from the command line using node test.js?
You would need to export double.js as a module, and then import that module into test.js. Should look something like this:
// double.js
var double_num = function(num){
return num*2;
}
// export your `double_num` function as a module so
// we can import this elsewhere in our programs
modules.export = double_num;
And in test.js make sure to include double.js by using its relative path to test.js. Assuming that they're in the same directory, it might look something like this:
// test.js
// Import `double_num` from the file we just exported it from
var double_num = require('./double_num');
var result = double_num(5);
console.log(result);

Categories