[英]JSX not allowed in files with extension ' .js' with eslint-config-airbnb
我已經安裝了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 代碼的 .js 文件進行 linting 處理時出現以下錯誤:
error JSX not allowed in files with extension '.js' react/jsx-filename-extension
如前所述,eslint-config-airbnb 是否已配置為支持 JSX?
應該怎么做才能消除該錯誤?
將您的文件擴展名更改為.jsx
或禁用jsx-filename-extension規則。 您可以將以下內容添加到您的配置中以允許 JSX 的.js
擴展。
"rules": {
"react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
}
這對我有用。 希望能幫到你。
在.eslintrc
禁用 jsx-filename-extension :
“規則”:{“反應/jsx-文件名-擴展名”:[0]}
在webpack.config.js
:
解析:{ 擴展名:['.js', '.jsx'] },
如果它不適合你,請叫我傻瓜
"rules": {
"react/jsx-filename-extension": [0],
"import/extensions": "off"
}
如果不想更改文件擴展名,可以導出返回 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);
以下React 文檔:
每個 JSX 元素只是調用 React.createElement(component, props, ...children) 的語法糖。
遵循Airbnb的風格指南:
不要使用 React.createElement ,除非你從一個不是 JSX 的文件初始化應用程序。
你可以這樣做:
//index.js
const app = React.createElement(App);
ReactDOM.render(app, document.getElementById('root'));
對於未來想要在.js
文件中編寫 jsx 的讀者:
npm i react react-dom
即使你認為你不是在寫 react。npm i -D @babel/preset-react
plugins: ['@babel/plugin-transform-react-jsx']
babel-loader
為/\.jsx?$/
文件設置module.rules
(因此您也需要安裝npm i -D babel-loader
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.