首页 文章

在带有eslint-config-airbnb的扩展名为' .js'的文件中不允许使用JSX

提问于
浏览
48

我已经安装了eslint-config-airbnb,它应该为React预先配置ESLINT:

我们的默认导出包含所有ESLint规则,包括ECMAScript 6和React . 它需要eslint,eslint-plugin-import,eslint-plugin-react和eslint-plugin-jsx-a11y .

我的 .eslintrc 扩展了它的配置:

{ "extends": "eslint-config-airbnb",
  "env": {
    "browser": true,
    "node": true,
    "mocha": true
  },
  "rules": {
    "new-cap": [2, { "capIsNewExceptions": ["List", "Map", "Set"] }],
    "react/no-multi-comp": 0,
    "import/default": 0,
    "import/no-duplicates": 0,
    "import/named": 0,
    "import/namespace": 0,
    "import/no-unresolved": 0,
    "import/no-named-as-default": 2,
    "comma-dangle": 0,  // not sure why airbnb turned this on. gross!
    "indent": [2, 2, {"SwitchCase": 1}],
    "no-console": 0,
    "no-alert": 0,
    "linebreak-style": 0
  },
  "plugins": [
    "react", "import"
  ],
  "settings": {
    "import/parser": "babel-eslint",
    "import/resolve": {
      "moduleDirectory": ["node_modules", "src"]
    }
  },
  "globals": {
    "__DEVELOPMENT__": true,
    "__CLIENT__": true,
    "__SERVER__": true,
    "__DISABLE_SSR__": true,
    "__DEVTOOLS__": true,
    "socket": true,
    "webpackIsomorphicTools": true
  }
}

不幸的是,当我在其中使用React JSX代码linting一个.js文件时,我收到以下错误:

error  JSX not allowed in files with extension '.js'              react/jsx-filename-extension

是不是已经配置了eslint-config-airbnb反应来支持JSX?

应该怎么做才能消除这个错误?

4 回答

  • 0

    如上所述,将文件扩展名更改为 .jsx 或禁用jsx-filename-extension规则 . 您可以将以下内容添加到配置中以允许JSX的 .js 扩展 .

    "rules": {
      "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
    }
    
  • 104

    这对我有用 . 希望能帮到你 .

    • .eslintrc 中禁用jsx-filename-extension:

    “rules”:{“react / jsx-filename-extension”:[0]}

    • in webpack.config.js

    解决:{extensions:[' . js',' . jsx']},

  • 1

    为了解释Martin's答案,目前似乎不可能在React Native中使用 JSX . A PR已创建但由于担心像 index.ios.jsx 这样的事情造成的碎片和未知后果而被恢复 . 我不确定AirBnb是如何解决这个问题的,或者如果他们这样做,但我使用的基本上和马丁一样使用了 rules 块 .

  • 6

    如果您不想更改文件扩展名,可以导出返回jsx的函数,然后在js文件中导入并调用该函数 .

    // greeter.jsx
    
    import React from 'react';
    
    export default name => (
      <div>
        {`Hello, ${name}!`}
      </div>
    );
    

    然后

    // index.js
    
    import ReactDOM from 'react-dom';
    import greeter from './components/greeter';
    
    const main = document.getElementsByTagName('main')[0];
    
    ReactDOM.render(greeter('World'), main);
    

相关问题