ES6 从根导入 [英] ES6 import from root

查看:30
本文介绍了ES6 从根导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在玩 React Native.我正在尝试构建我的应用程序,但它开始变得与导入混乱.

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

现在,在我的 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';

我知道首选的解决方案是为事物制作私有的 npm 模块,但这对于小项目来说太过分了.

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

你可以在浏览器上做一个 global.requireRoot 类型的解决方案,但我如何通过导入来实现它?

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

推荐答案

在 React 中遇到了同样的问题.所以我为 babel 编写了一些插件,它可以从根的角度导入模块 - 路径不短 - 但很清楚你导入的内容.

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.

所以代替:

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

您可以使用:

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

这是插件(经过测试并带有清晰的自述文件)

这篇关于ES6 从根导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆