简体   繁体   中英

How to fix “SyntaxError: Cannot use import statement outside a module”

I am trying to put together my first React Typescript JSX component npm package.

I copied working code from a CRA TypeScript project to an empty folder and added the following package.json and tsconfig.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"]
}

When I import react-hashlink using npm link and npm link react-hashlink in a project, the following error is thrown.

SyntaxError: Cannot use import statement outside a module

I am likely missing something. Ideas?

Using "module": "commonjs" and "target": "esnext" did the job!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM