简体   繁体   English

导入函数的正确方法

[英]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.在了解了 javascript 承诺及其行为方式的一些非常有用的提示之后,我正在寻求一些帮助,以将函数从一个 javascript 文件正确导入/导出到另一个通过 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". 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 “你好”代替“欢迎使用 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基本的.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改变.js

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

module.exports={changeThis};

basicNode.js基本节点.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.在您的change.js文件中,您将 function 作为命名导出导出。 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.如果您只从文件中导出一个 function(这不是规则),通常使用命名导出,而命名导出主要用于从文件中导出多个函数时。

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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