ES6 import from root

2019-02-08 03:07发布

I'm currently playing around with React Native. I'm trying to structure my app, however it's starting to get messy with imports.

--app/
    -- /components
        -- Loading.js
    -- index.ios.js

Now, within my index.ios.js i'm able to simply do:

import Loading from './components/Loading';

However, when I start to create more components, with a deeper directory struture, it starts to get messy:

import Loading from '.../../../../components/Loading';

I understand the preferred solution would be to make private npm modules for things, but that's overkill for a small project.

You could do a global.requireRoot type solution on the browser, but how do I implement this with import?

7条回答
疯言疯语
2楼-- · 2019-02-08 04:01

If you're using Create React App you can add paths.appSrc to resolve.modules in config/webpack.config.dev.js and config/webpack.config.prod.js.

From:

resolve: {
    modules: ['node_modules', paths.appNodeModules].concat(...

To:

resolve: {
    modules: [paths.appSrc, 'node_modules', paths.appNodeModules].concat(...

Your code would then work:

import Loading from 'components/Loading';
查看更多
登录 后发表回答