This was interview question for me. How we can access a function defined in one.js in two.js?
I told them an answer using HTML, but they were looking for an answer that didn't involve linking via the HTML.
How is this possible?
This was interview question for me. How we can access a function defined in one.js in two.js?
I told them an answer using HTML, but they were looking for an answer that didn't involve linking via the HTML.
How is this possible?
If you can control the script tag of one.js
, make it a module, and import
from two.js
:
<script type="module" src="one.js">
// one.js
import { foo } from './two.js';
foo();
// two.js
export const foo = () => {
console.log('foo running');
};
ES6 modules in the browser aren't supported everywhere, but they're supported on most modern browsers.
They might have been asking for Node.js require
.
Here is an example of what that might look like, calling a function from one.js
in two.js
:
// one.js
module.exports = function () {
console.log('Hello World')
}
// two.js
const myFunction = require('./two.js')
myFunction()