.jsx和.js文件后缀类型有何区别?

outsiderlcy 2019-12-05

学react,发现有的项目里有.jsx文件,这是什么文件类型?

首先.jsx文件后缀类型(extension)和JSX语法不是一回事。

网上看了下(见末尾参考),结论是:没有什么区别!用哪种后缀都可以,统一代码风格就好。

.jsx文件和.js文件后缀是可以互换的,语法内容完全通用,.jsx文件就是js文件。

那为什么要用.jsx后缀文件名呢?

Valentin D. https://dev.to/yashyashwanth/jsx-extension-5ffe 写道
You can always use .js extension if you want, but it's generally better to use .jsx when your file contains JSX so it's simpler for you to understand what the file will actually contain.

.js --> only js
.jsx --> contains JSX (reactjs.org/docs/introducing-jsx.html)

 还有Airbnb团队支持使用.jsx后缀,理由是:

https://github.com/airbnb/javascript/pull/985#issuecomment-237038754 写道
Thanks, but no. At Airbnb we believe that only JavaScript should ever go in .js files. JSX is not standard JS, and is not likely to ever be - if that changes, then our stance may as well.

You never need extensions whether it's .js or .jsx - and in fact, our linter config requires (or will soon require) that you omit file extensions in all cases.

The reason to differentiate is the same reason we only use stage 3 and above proposals: if it's not standard, it is not javascript.

 认为JSX语法不是标准的js语法,鼓励在.js文件里使用标准JS语法,如果包含JSX语法就用.jsx文件名表明。

同理,使用typescript等扩展语法的js文件,就用.ts扩展名。

https://github.com/airbnb/javascript/issues/1235#issuecomment-428413675 写道
It seems like the react team at facebook and the airbnb team that own the most popular javascript style guide here are at odds with each other over file extensions.

Airbnb team seems adamant about not having any non standard code in a js file re this issue (#1235)

and this pull #985

and names any files with the stuff should have jsx

Facebook team seems adamant that js should be the only extension no matter what is in the file

facebook/create-react-app#87 (comment)

For my (and probably others) future reference when setting up a new js repo with the eslint-config-airbnb

 Facebook团队貌似观点与Airbnb不同,认为统一用.js文件名就可以了,不需要特意区分。

 eslint中使用 eslint-config-airbnb 风格规范的,对包含JSX语法的js文件可能会有些提示?(没有验证过)

 基本上用哪个后缀名都一样,只要编译器/打包等构建工具/IDE能正确识别处理好,最后生成正常运行工作的js就好。

对于新手来说,貌似react纯视图层组件,用jsx扩展名更容易识别,区分与其他状态组件(redux)

兼容性上看js文件名方便,不需额外处理识别其他文件名后缀类型,或者统一处理?以不变应万变?= =

 参考链接:

https://github.com/airbnb/javascript/pull/985

https://github.com/airbnb/javascript/issues/1235

https://stackoverflow.com/questions/46169472/reactjs-js-vs-jsx

https://dev.to/yashyashwanth/jsx-extension-5ffe

相关推荐