node.js - 语法错误: Cannot use import statement outside a module using puppeteer

标签 node.js npm module syntax-error puppeteer

您好,我一直尝试运行 puppeteer 测试,但不断遇到此问题。请帮忙谢谢。 enter image description here 代码:

import puppeteer from 'puppeteer';

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.goto('https://developers.google.com/web/');

  // Type into search box.
  await page.type('.devsite-search-field', 'Headless Chrome');

  // Wait for suggest overlay to appear and click "show all results".
  const allResultsSelector = '.devsite-suggest-all-results';
  await page.waitForSelector(allResultsSelector);
  await page.click(allResultsSelector);

  // Wait for the results page to load and display the results.
  const resultsSelector = '.gsc-results .gs-title';
  await page.waitForSelector(resultsSelector);

  // Extract the results from the page.
  const links = await page.evaluate(resultsSelector => {
    return [...document.querySelectorAll(resultsSelector)].map(anchor => {
      const title = anchor.textContent.split('|')[0].trim();
      return `${title} - ${anchor.href}`;
    });
  }, resultsSelector);

  // Print all the files.
  console.log(links.join('\n'));

  await browser.close();
})();

错误:

SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:74:18)
    at wrapSafe (node:internal/modules/cjs/loader:1128:20)
    at Module._compile (node:internal/modules/cjs/loader:1169:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1259:10)
    at Module.load (node:internal/modules/cjs/loader:1068:32)
    at Module._load (node:internal/modules/cjs/loader:909:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
    at node:internal/main/run_main_module:23:47

我尝试重新安装 Node js 和 npm,但没有任何效果。

最佳答案

{
 "name": "my-app",
 "version": "0.0.0",
 "type": "module",
 "scripts": { ...
 },
   ...
 }

在 package.json 文件中添加 type:module 或安装最新的 Nodejs

关于node.js - 语法错误: Cannot use import statement outside a module using puppeteer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74650098/

相关文章:

node.js - Mongoose 查询 where

node.js - 模块 '"typeorm "' has no exported member ' DataSource' 和 'DataSourceOptions'

python - 关于Python中正弦、余弦、正切函数的问题

python - 存储和加载 str :func Python dictionaries

java - Gradle : How to run tests from a module dependency?

node.js - 如何在 Express 4.0 路由器中间件中重用 MongoClient 对象?

javascript - Cypress 是否需要 Node.js 才能获得完整功能?

javascript - 将数组对象转换为所需格式的对象数组

node.js - 无法从注册表加载包信息 : The "timeout" argument must be of type number. 收到类型字符串 ('100000' )

javascript - lodash 怎么会有一个驻留在不在存储库中的目录中的构建脚本?