如何修复“语法错误:无法在模块外使用导入语句”

时间:2021-01-17 12:53:21

标签: reactjs typescript

我正在尝试组合我的第一个 React Typescript JSX 组件 npm 包。

我将 CRA TypeScript 项目中的工作代码复制到一个空文件夹中,并添加了以下 package.jsontsconfig.json

package.json

{
  "name": "react-hashlink",
  "version": "0.0.1",
  "description": "React hash link",
  "main": "lib/HashLink.js",
  "keywords": [
    "react",
    "hash",
    "link"
  ],
  "peerDependencies": {
    "react": "^17.0.0",
    "react-dom": "^17.0.0",
    "react-router-dom": "^5.0.0"
  },
  "dependencies": {},
  "devDependencies": {
    "@types/react": "^17.0.0",
    "@types/react-router-dom": "^5.1.7",
    "@types/styled-components": "^5.1.7",
    "npm-check-updates": "^10.2.5",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0",
    "typescript": "^4.1.3"
  },
  "scripts": {
    "code": "tsc -w",
    "build": "rm -fr lib/*; tsc",
    "ncu": "ncu -u"
  },
  "prettier": {
    "endOfLine": "lf",
    "printWidth": 80,
    "semi": false,
    "tabWidth": 2,
    "trailingComma": "es5"
  }
}

tsconfig.json

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

当我在项目中使用 react-hashlinknpm link 导入 npm link react-hashlink 时,抛出以下错误。

<块引用>

语法错误:不能在模块外使用导入语句

我可能遗漏了一些东西。想法?

1 个答案:

答案 0 :(得分:0)

使用 App / \ Module1 \ \ \ \ \ \ \ Module2 "module": "commonjs" 做到了!