【问题标题】:How to add src folder to React-native and import absolutely?如何将 src 文件夹添加到 React-native 并绝对导入?
【发布时间】:2019-09-09 15:25:49
【问题描述】:

我正在尝试添加 src 目录,这样我就有了类似的东西

- package.json
- android
- ios
- src
   - foo
     - hello.js
- index.js
- App.js
- node_modules

然后我添加了

watchFolders: [path.join(__dirname, 'src')],

metro.config.js

希望能够在任何地方做import hello from 'foo/hello'(例如来自App.js

我还发现如果在node_modules下添加文件夹就可以实现absolute import

- package.json
- android
- ios
- node_modules
   - foo
     - hello.js
- index.js
- App.js

【问题讨论】:

    标签: react-native metro-bundler


    【解决方案1】:

    src文件夹内创建一个package.json,内容如下

    {
        "name": "src"
    }
    

    然后你可以像这样引用其他文件 import hello from 'src/foo/hello'

    您也可以查看video

    【讨论】:

      【解决方案2】:

      您需要在 foo 文件夹中创建一个 index.js 文件

      index.js

       import hello from './hello.js'
      
          export{
            hello
          }
      

      您想将文件导入到哪里

      其他文件.js

      import hello from '../../src/foo'
      

      【讨论】:

        猜你喜欢
        • 2023-03-05
        • 1970-01-01
        • 2021-05-26
        • 1970-01-01
        • 1970-01-01
        • 2013-07-11
        • 1970-01-01
        • 2015-12-31
        • 1970-01-01
        相关资源
        最近更新 更多