Export/Import Nightmare.js 函数
Export/Import Nightmare.js functions
所以,我有一个可用的 nightmare.js 应用程序,它可以 100% 运行。我现在处于重构阶段,想将我制作的自定义函数(使用 nightmare.js 函数)放入另一个文件,然后 export/import 将它们放入我的主文件中。
函数被调用,但噩梦函数实际上并没有执行或抛出错误。
为什么噩梦函数在导入时不起作用?
我的主要应用程序:
const Nightmare = require('nightmare')
const nightmare = Nightmare({
show: true,
typeInterval: 1000,
waitTimeout: 60 * 1000
})
const bot = require('./utils')
nightmare
.goto(url)
.then(_ => bot.selectByVal('#myDiv', 'myVal'))
.then( 'yada yada yada ...')...
module.exports = nightmare;
实用程序:
const Nightmare = require('nightmare');
const nightmare = Nightmare();
module.exports = {
selectByVal: function(el, val) {
console.log('select' + el + val)
try {
return nightmare.select(el, val)
} catch (e) {
return e
}
}
}
我认为这与我的噩梦实例不是 exported/imported 有关,但不确定该怎么做。
bot
或 utils
无权访问在主应用程序上创建的 nightmare
。您需要传递引用。
Return 一个函数而不是 returns 一个对象。
module.exports = function(nightmare) { // <-- now the same nightmare is in both file
return {
selectByVal: function(el, val) {
console.log('select' + el + val)
try {
return nightmare.select(el, val)
} catch (e) {
return e
}
}
}
}
然后在您的主应用上,
const bot = require('./utils')(nightmare) // <-- pass the reference
nightmare
.goto(url)
.then(_ => bot.selectByVal('#myDiv', 'myVal'))
所以,我有一个可用的 nightmare.js 应用程序,它可以 100% 运行。我现在处于重构阶段,想将我制作的自定义函数(使用 nightmare.js 函数)放入另一个文件,然后 export/import 将它们放入我的主文件中。
函数被调用,但噩梦函数实际上并没有执行或抛出错误。
为什么噩梦函数在导入时不起作用?
我的主要应用程序:
const Nightmare = require('nightmare')
const nightmare = Nightmare({
show: true,
typeInterval: 1000,
waitTimeout: 60 * 1000
})
const bot = require('./utils')
nightmare
.goto(url)
.then(_ => bot.selectByVal('#myDiv', 'myVal'))
.then( 'yada yada yada ...')...
module.exports = nightmare;
实用程序:
const Nightmare = require('nightmare');
const nightmare = Nightmare();
module.exports = {
selectByVal: function(el, val) {
console.log('select' + el + val)
try {
return nightmare.select(el, val)
} catch (e) {
return e
}
}
}
我认为这与我的噩梦实例不是 exported/imported 有关,但不确定该怎么做。
bot
或 utils
无权访问在主应用程序上创建的 nightmare
。您需要传递引用。
Return 一个函数而不是 returns 一个对象。
module.exports = function(nightmare) { // <-- now the same nightmare is in both file
return {
selectByVal: function(el, val) {
console.log('select' + el + val)
try {
return nightmare.select(el, val)
} catch (e) {
return e
}
}
}
}
然后在您的主应用上,
const bot = require('./utils')(nightmare) // <-- pass the reference
nightmare
.goto(url)
.then(_ => bot.selectByVal('#myDiv', 'myVal'))