【问题标题】:Does React Native use require or import?React Native 使用 require 还是 import?
【发布时间】:2016-09-12 23:40:34
【问题描述】:

React Native 使用require 还是import

我只能找到一个使用require() 的旧教程,但是当我运行react-native init 时,我得到了一个使用import 的项目。这是由于最近 React Native 的变化造成的吗?

主要区别是什么?

【问题讨论】:

    标签: react-native


    【解决方案1】:

    是的,最新的 React Native 教程和示例使用新的 import 语法。

    https://facebook.github.io/react-native/docs/tutorial.html

    关于 CommonJS (require) 和 ES6 modules (import) 的区别,这里有一些很好的答案:

    Using Node.js require vs. ES6 import/export

    我认为大多数人更喜欢新的 ES6 语法。但是目前没有 JS 引擎实现 ES6 模块,因此需要通过 ES6 转译器(例如 Babel)将其转换为 require 语句。 React Native 设置为开箱即用,因此您可以开始使用import,它应该可以正常工作。

    【讨论】:

      【解决方案2】:

      主要区别在于,import 是 ECMAScript 6 语法,require 是 ECMAScript 5。两者可以互换,但 import 有一个很好的重命名语法:export { MY_CONST as THE_CONST, myFunc as theFunc };

      【讨论】:

        【解决方案3】:

        React Native 现在使用 Babel 进行“模块”编译 (doc)。如果用create-react-native-app 搭建应用程序,则在文件夹node_modules 中,有the Babel plugin 命名

        babel-plugin-transform-es2015-modules-commonjs
        

        ,在整个应用程序中引用。

        顾名思义,这个插件只是将 ES2015 模块语法转换为 CommonJS。

        对于主要区别,我喜欢 this answer 出现在另一个帖子中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-27
          • 1970-01-01
          • 1970-01-01
          • 2020-05-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-31
          相关资源
          最近更新 更多