[英]How to import a JavaScript file to another JavaScript file
I was trying to import a JavaScript file to my server side JavaScript file because I can't run the function on my server side.我试图将一个 JavaScript 文件导入我的服务器端 JavaScript 文件,因为我无法在我的服务器端运行该函数。 Is there any way to import my src to server side js so that I can run the function.有什么方法可以将我的 src 导入服务器端 js 以便我可以运行该函数。 Thanks in advance.提前致谢。
JS file to export to server side JS文件导出到服务器端
const {Builder, By, Key, util} = require("selenium-webdriver");
(async function googlesearch() {
let driver = await new Builder().forBrowser('chrome').build();
try{
await driver.get("https://www.google.com/");
let searchField = await driver.findElement(By.name('q'));
await searchField.sendKeys("workout videos");
await searchField.sendKeys(Key.ENTER);
await driver.wait(until.titleIs('workout videos - Google Search'), 5000);
let list = await driver.findElements(By.className('g'));
if(list.length <= 0 ){
throw new Error('Test - FAIL');
}else{
console.log('Test - Success');
}
} finally {
console.log("automation complete")
}
})();
i think you could something like我想你可以像
const {Builder, By, Key, util} = require("selenium-webdriver");
exports.googlesearch = async () => {
let driver = await new Builder().forBrowser('chrome').build();
try{
await driver.get("https://www.google.com/");
let searchField = await driver.findElement(By.name('q'));
await searchField.sendKeys("workout videos");
await searchField.sendKeys(Key.ENTER);
await driver.wait(until.titleIs('workout videos - Google Search'), 5000);
let list = await driver.findElements(By.className('g'));
if(list.length <= 0 ){
throw new Error('Test - FAIL');
}else{
console.log('Test - Success');
}
} finally {
console.log("automation complete")
}
}
so you can import as所以你可以导入为
const { googlesearch } = require('./file/path')
Use module.exports in the file you want to import using Commonjs modules.使用module.exports文件中你想使用CommonJS的模块导入。
For example例如
const {Builder, By, Key, util} = require("selenium-webdriver");
async function googlesearch() {
let driver = await new Builder().forBrowser('chrome').build();
try{
await driver.get("https://www.google.com/");
let searchField = await driver.findElement(By.name('q'));
await searchField.sendKeys("workout videos");
await searchField.sendKeys(Key.ENTER);
await driver.wait(until.titleIs('workout videos - Google Search'), 5000);
let list = await driver.findElements(By.className('g'));
if(list.length <= 0 ){
throw new Error('Test - FAIL');
}else{
console.log('Test - Success');
}
} finally {
console.log("automation complete")
}
});
// this was added here:
module.exports.googlesearch = googlesearch;
Then import/require it like this:然后像这样导入/要求它:
const {googlesearch} = require("./yourfilename");
or if you're using js modules export it like this:或者,如果您使用的是 js 模块,请像这样导出它:
export googlesearch;
And to import:并导入:
import {googlesearch} from "./yourfilename";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.