如何修复“SyntaxError: Cannot use import statement outside a module”错误。

5

我试图创建我的第一个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"]
}

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

SyntaxError: Cannot use import statement outside a module

我可能漏掉了什么。有什么想法吗?

这个回答解决了你的问题吗?在导入ECMAScript 6时出现“Uncaught SyntaxError:Cannot use import statement outside a module”的错误。 - Or Assayag
感谢@OrAssayag的帮助。请查看下面的答案。 - sunknudsen
1个回答

0

使用 "module": "commonjs""target": "esnext" 就可以完成任务了!


1
"module": "commonjs" 和 "target": "esnext" 对我没有起作用。 - skate_23

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接