Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - ES6 import from root

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Had the same issue with React. So i wrote some plugin for babel which make it possible to import the modules from the root perspective - the paths are not shorter - but it's clear what you import.

So instead of:

import 'foo' from '../../../components/foo.js';

You can use:

import 'foo' from '~/components/foo.js';

Here is the Plugin (tested and with a clear README)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...