移动 Create React App 文件夹会破坏正在运行的应用程序

Moving Create React App folder breaks working app

我用 create-react-app 创建了一个基本的 React web 应用程序,它在弹出后具有以下结构。工作正常。

intended-app-home
  |- the-app
      |- config
      |- node_modules
      |- public
      |- scripts
      |- src
      |- package.json
  |- .eslintignore
  |- .eslintrc
  |- .gitignore

现在,我想将 the-app 的内容移动到文件夹 intended-app-home 的上一层。当我这样做时,当 运行 npm start:

时出现以下错误
Failed to compile.

Error in ./src/index.js

  1:1  error  Parsing error: 'import' and 'export' may appear only with 'sourceType: module'

✖ 1 problem (1 error, 0 warnings)


Error in ./src/components/Blah.js

  1:1  error  Parsing error: 'import' and 'export' may appear only with 'sourceType: module'

我错过了什么?假设app文件夹是可移植的不安全吗?

这是我的 .eslintrc 内容:

{
  "extends": "eslint:recommended",
  "env": {
    "browser": true,
    "commonjs": true,
    "node": true,
    "es6": true
  },
  "parserOptions": {
    "ecmaVersion": 6
  },
  "rules": {
    "no-console": "off",
    "strict": ["error", "global"]
  }
}

您必须按照错误提示将以下内容添加到 .eslintrc

"parserOptions": {
  "sourceType": "module"
}

根据 the ESLint documentation:

  • sourceType - set to "script" (default) or "module" if your code is in ECMAScript modules.

问题是,在 ECMAScript 2015 中,有脚本和模块之类的东西。脚本只是普通的 JavaScript 文件。另一方面,模块是导出数据的脚本 and/or 导入其他模块。因此,如果您想使用 importexport,您必须指定 "sourceType": "module" 以便 ESLint 可以使用 Espree 正确解析您的模块代码并对其进行 lint。

现在解释为什么仅当您将 the-app 内容上移一级时才会发生错误。默认情况下,Create React App 为其项目使用以下 ESLint 配置,在 package.json:

中指定
"eslintConfig": {
  "extends": "react-app"
}

所以 ESLint 配置只是扩展了 React App 配置。如果您查看 eslint-config-react-app, in index.js 的来源:

parserOptions: {
  ecmaVersion: 6,
  sourceType: 'module',
  ecmaFeatures: {
    jsx: true,
    generators: true,
    experimentalObjectRestSpread: true,
  },
},

因此,默认情况下,Create React App 的 ESLint 配置将 sourceType 设置为 module。当您尝试将 the-app 的内容上移一级时,就会出现问题。由于您的 .eslintrc 指定 sourceType,因此使用默认值 script。并且由于 .eslintrc 从 Create React App1 覆盖了 package.json 中的 ESLint,错误发生是因为你不能使用 importexport 在脚本中。


如果您想添加新规则,则不应创建新的 ESLint 配置文件。相反,只需编辑 package.json:

中已有的配置
"eslintConfig": {
  "extends": ["eslint:recommended", "react-app"],
  "rules": {
    "no-console": "off",
    "strict": ["error", "global"]
  }
}

请注意,eslint-config-react-app 已经为您设置了 env


1 如果选中 the ESLint source,默认 CLI 选项是使用 .eslintrc 如果文件存在于 eslintConfig package.json,见属性useEslintrc: true。因此它被覆盖的原因。

如果上述方法没有帮助,删除 ios/build 文件夹 和 运行 再次对我有用。

即从你的新根文件夹

 rm -r ios/build
 npx react-native run-ios

每个答案在 https://github.com/facebook/react-native/issues/18793