缩短ES2015导入路径

时间:2016-04-29 16:15:56

标签: javascript webpack ecmascript-6 babeljs

我正在开发一个大型ES2015项目,该项目有很多import语句引用深层目录结构中的库。目前,进口采取

的形式
import Status from '../../../Scripts/core/components/Status';
//import ...

除了更改源文件的位置之外,是否有任何缩短导入路径长度的变通方法?

编辑:我正在使用带webpack的babel-loader来编译模块。

3 个答案:

答案 0 :(得分: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 :(得分: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"

答案 2 :(得分:0)

另一种可能性是Babel的resolveModuleSource选项,但请注意,它只能以编程方式配置,而不能通过.babelrc配置,并且仅适用于Babel编译的模块语法。因此,例如,如果您需要从Babel编译的非模块语法的代码中引用lib,那可能有利于通过bundler(Webpack)或将lib放在node_modules中(与您无关紧要)正如其他人在评论中所建议的那样,“不要将其发布到npm”。

请注意,如果您通过捆绑程序执行此操作,则只能在捆绑的输出中使用,而不是直接在Node中运行代码/使用Babel的require钩子。因此,请考虑您将如何测试此代码。你打算捆绑测试吗?您可能希望在组合中或在不同的上下文中使用其中几个选项。