简体   繁体   English

使用puppeteer从另一个文件导入javascript函数?

[英]Import javascript function from another file with puppeteer?

This is a noob question. 这是一个菜鸟问题。 I've been developing in React for a while now and I'm used to breaking up my code into components. 我已经在React中开发了一段时间了,我习惯于将代码分解为组件。

I've started a new project using puppeteer.js. 我已经使用puppeteer.js开始了一个新项目。 I'd like to break my javascript function up into components as well but I have no idea how to import a function from another file. 我也想将我的javascript函数分解为组件,但是我不知道如何从另一个文件导入函数。

Is this possible? 这可能吗?

Path: main.js 路径: main.js

const puppeteer = require("puppeteer");
import {myFunction} from './myFunction.js';

(async function main() {
  try {
    // launch puppeteer
    const browser = await puppeteer.launch({ headless: false });
    // open browser
    const page = await browser.newPage();
    await page.setViewport({}); 

    const callMyFunction = await myFunction(page);

  } catch (e) {
    console.log("our error", e);
  }
})();

Path: myFunction.js 路径: myFunction.js

async function myFunction(page) {
  console.log('this function has been imported');
  return true;
}

export default myFunction;

try 尝试

//myFunction.js
async function myFunction(page) {
  console.log('this function has been imported');
  return true;
}
module.exports = myFunction;
//main.js
const puppeteer = require('puppeteer');
const myFunction = require('./myFunction');

(async function main() {
  try {
    // launch puppeteer
    const browser = await puppeteer.launch({ headless: false });
    // open browser
    const page = await browser.newPage();
    await page.setViewport({}); 

    const callMyFunction = await myFunction(page);

  } catch (e) {
    console.log("our error", e);
  }
})();

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

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