React JS SyntaxError:不能在模块外使用导入语句

时间:2021-02-20 10:14:11

标签: node.js reactjs typescript npm redux

我正在尝试使用 package.json 运行在 ts-node 中定义的名为 foo 的 NPM 脚本,但会引发以下错误。

<块引用>

(node:94440) 警告:要加载 ES 模块,请在 package.json 中设置 "type": "module" 或使用 .mjs 扩展名。 (使用 node --trace-warnings ... 显示警告的创建位置) /Users/vinaysharma/Sites/projects/the-seasoned-dev/src/scripts/foo.ts:1 从 './bar' 导入 { x }; ^^^^ 语法错误:不能在模块外使用导入语句

以下是我尝试使用 npx ts-node src/scripts/foo.ts 运行的文件。

脚.ts

import { x } from './bar';

console.log(x);

bar.ts

export const x = 1;

文件夹结构

|_node_modules
|_public
|_src
| |_scripts
| | |_foo.ts
| | |_bar.ts
| |_App.tsx
| |_App.css
| |_index.tsx
| |_index.css
|_package.json
|_package-lock.json
|_tsconfig.json

Package.json

{
  "name": "project-name",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.9",
    "@testing-library/react": "^11.2.5",
    "@testing-library/user-event": "^12.6.3",
    "@types/jest": "^26.0.20",
    "@types/node": "^12.19.16",
    "@types/react": "^17.0.1",
    "@types/react-dom": "^17.0.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.2",
    "typescript": "^4.1.3",
    "web-vitals": "^1.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "foo": "npx ts-node src/scripts/foo.ts"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "ts-node": "^9.1.1"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"]
}

0 个答案:

没有答案
相关问题