2016-04-29 70 views
1

我的工作,有很多import语句指的是图书馆在深目录结构的大ES2015项目。目前,进口采取的缩短ES2015进口路径

import Status from '../../../Scripts/core/components/Status'; 
//import ... 

形式是否有任何变通办法缩短进口路径不是改变源文件的位置,其他的长度?

编辑:我使用的巴别塔,装载机的WebPack编译模块。

+0

由于ES2015模块实际上并没有任何的JavaScript引擎实现的,您的问题的答案将在很大程度上取决于您使用什么技术来伪造ES2015模块。你应该在你的问题中包含它。例如,这些“Babel模块”或“TypeScript模块”,还是......? – Domenic

+0

模块加载器不是ECMAScript的一部分。你必须阅读你用来加载模块的环境/工具文档,如果他们提供了一个选项。所以,这与ES6无关,但与您使用的环境/工具无关。 –

+0

好点,我编辑帖子,添加我使用webpack + babel。 – aiokos

回答

4

您还可以使用resolve.alias来处理可能走动根:

resolve: { 
    alias: { 
    importName: 'actual/path/here', 
    '__another_alias__': 'another/path' 
    } 
} 

然后你可以为使用:

import someImport from 'importName'; 
import anotherImport from '__another_alias__/sub/path'; 
1

一个常见的模式是有进口相似背景的所有组件的单一文件,然后导出他们所有。然后你可以从这个单一文件中的import树中的更高层次。例如,Angular2确实this

/** 
* @module 
* @description 
* Starting point to import all public core APIs. 
*/ 
export * from './src/core/metadata'; 
export * from './src/core/util'; 
export * from './src/core/prod_mode'; 
export * from './src/core/di'; 
export * from './src/facade/facade'; 
export {enableProdMode} from 'angular2/src/facade/lang'; 
export { 
    createPlatform, 
    assertPlatform, 
    disposePlatform, 
    getPlatform, 
    coreBootstrap, 
    coreLoadAndBootstrap, 
    createNgZone, 
    PlatformRef, 
    ApplicationRef 
} from './src/core/application_ref'; 
export { 
    APP_ID, 
    APP_INITIALIZER, 
    PACKAGE_ROOT_URL, 
    PLATFORM_INITIALIZER 
} from './src/core/application_tokens'; 
export * from './src/core/zone'; 
export * from './src/core/render'; 
export * from './src/core/linker'; 
export {DebugElement, DebugNode, asNativeElements} from './src/core/debug/debug_node'; 
export * from './src/core/testability/testability'; 
export * from './src/core/change_detection'; 
export * from './src/core/platform_directives_and_pipes'; 
export * from './src/core/platform_common_providers'; 
export * from './src/core/application_common_providers'; 
export * from './src/core/reflection/reflection'; 

正如你所看到的,而不是必须import {Foo} from './src/core/platform_common_providers'比如你根本就import {Foo} from "angular2/core"

+1

Ahhhhh。我假设Angular的源代码树在一个TypeScript文件中基本上有5个类。我已经开始在一个源文件中用几个小类来设计我的模块,据说模仿它们。这更有意义。 – Katana314

+1

这非常有帮助,我打算查看这个和webpack别名,看看哪一个更适合我的用例。 – aiokos

0

另一种可能性是通天的resolveModuleSource选择,但要注意,它只能通过编程的方式不是通过.babelrc配置,并且是只适用于Babel编译的模块语法。因此,举例来说,如果你需要从代码,这不是语法模块由巴贝尔编译,这可能有利于通过捆绑(的WebPack)或投入node_modules的lib(没关系这样做,你是不是发布引用的lib它到npm)正如其他人在评论中所建议的那样。

请注意,如果您通过捆绑做到这一点,那将只能在捆绑的输出工作,而不是在节点直接运行的代码/使用巴贝尔的要求挂钩。因此,请考虑如何测试此代码。你打算捆绑测试吗?有可能您可能想要结合使用这些选项中的一些或在不同的环境中使用这些选项。