运行“纱线节点”时出现“ReferenceError: require is not defined”。

时间:2021-02-07 03:38:42

标签: javascript node.js yarnpkg

我第一次尝试打字稿和纱线,并在尝试运行 yarn node . 时遇到以下错误:

yarn node v1.22.10
file:///Users/stevenbarber/devl/MLBStatsSDK/lib/query.js:1
const axios = require('axios').default;
              ^

ReferenceError: require is not defined
    at file:///Users/stevenbarber/devl/MLBStatsSDK/lib/query.js:1:15
    at ModuleJob.run (node:internal/modules/esm/module_job:154:23)
    at async Loader.import (node:internal/modules/esm/loader:166:24)
    at async Object.loadESM (node:internal/process/esm_loader:68:5)
error Command failed.
Exit code: 1
Command: /usr/local/Cellar/node/15.8.0/bin/node
Arguments: .
Directory: /Users/stevenbarber/devl/MLBStatsSDK
Output:

ts.config 看起来像

{
    "compilerOptions": {
        "target": "es2020"
    },
    "module": "esnext"
}

package.json 看起来像

{
  "dependencies": {
    "@types/node": "^14.14.25",
    "axios": "^0.21.1",
    "dotenv": "^8.2.0",
    "typescript": "^4.1.3",
    "typings": "^2.1.1"
  },
  "type": "module",
  "private": true
}

index.ts 看起来像

require('dotenv').config()

import Players from './lib/player/players.js'

const players = new Players()
console.log(players.search('sosa', true))

并在我运行 tsc

时编译成这个
require('dotenv').config();
import Players from './lib/player/players.js';
const players = new Players();
console.log(players.search('sosa', true));

我发现的大多数建议往往涉及 require 不适用于客户端,并且只能在 node 中使用,但由于我在 node 中运行它,我不确定这如何适用。

另外值得注意的是,当我从 "type": "module" 中删除 package.json 时,正如一些人在其他线程中所建议的那样,我得到了这个:

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (node:internal/modules/cjs/loader:1024:16)
    at Module._compile (node:internal/modules/cjs/loader:1072:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47
error Command failed.
Exit code: 1
Command: /usr/local/Cellar/node/15.8.0/bin/node
Arguments: index.js
Directory: /Users/stevenbarber/devl/MLBStatsSDK
Output:

0 个答案:

没有答案