简体   繁体   中英

Proper method of importing functions

After some very helpful tips learning about javascript promises and how they behave, I am looking for some help with properly importing/exporting functions from one javascript file into another which is run via NodeJS.

Essentially I want basicNode.js to open an html doc, and then once that is open (and the promise implied via the open(html) statement is 100% complete/finalized) run the function from change.js to alter the html to show "Hello" in the place of "Welcome to JavaScript". This will provide proof of concept that can then be extrapolated for a project dealing with automating reports at my internship, so any help is greatly appreciated

basic.html

<!DOCTYPE html>
<html>  
<head>  
</head>  
<body>
<p>Date/Time: <span id="datetime"></span></p>
  
<p id="here">Welcome to JavaScript</p>  
<form>  
<input type="button" value="click" onclick="changeThis()"/>  
</form>  
</body> 
<script>
var dt = new Date();
    document.getElementById("datetime").innerHTML = dt.toLocaleString();
</script>
<script type="text/javascript" src="change.js"></script> 
<!--
<script>waitForElementToDisplay("#here",function(){alert("Hi");},1000,9000);</script> 
--> 
</html> 

change.js

function changeThis() {
    document.getElementById("here").innerHTML = "Hello";
}

module.exports={changeThis};

basicNode.js

const open = require('open');
var { change }  = require('./change')
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
global.document = new JSDOM('./basic.html').window.document;

const main = async () => {
  await open('./basic.html');
  change.changeThis();
}

main();

In your change.js -file you are exporting your function as a named export. A named export is normally used if you are only exporting one function from a file (this is not a rule), and named exports are mainly used when you are exporting several functions from a file.

This is a named export

module.exports= { changeThis };

A named export is imported as

var { changeThis }  = require('./change')

The opposite to a named export is a default export.

module.exports = changeThis

This is imported as

var changeThis = require("./change")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM