【问题标题】:How can I find the root Angular directory?如何找到根 Angular 目录?
【发布时间】:2017-08-16 19:59:36
【问题描述】:

编辑:虽然这个问题最初是关于服务的,我现在知道服务应该包含在模块中,但核心问题在应用于导入模块时仍然有效。现在文档已经(有些)发展了,下面有一个更新的答案,使用“官方”方式来做到这一点。

我想在我的模块/组件中引用一项服务。我所有的服务都在 /_services 目录中,当我知道我的服务总是在根目录下时,我不想向后遍历文件系统。如果我将我的组件移动到一个新的子目录中,我希望它能够适应这种简单的更改并且不需要返工。

换句话说,我可以改变这个吗:

import { ApiService } from './../../_services/api.service';

喜欢这样的东西?

import { ApiService } from '$APP_ROOT/_services/api.service';

【问题讨论】:

  • 看看这个:我不知道你是否使用 webpack 但HERE 你去
  • 另外this plugin 可能对你有帮助
  • 太棒了!您为什么不将这些作为答案发布? :) 我经常为 node 使用 approot 插件,这对于 Angular 来说似乎是一个很好的方法。
  • 我不知道您使用的是 AngularJs 还是 Angular2,但如果是 Angular2,您应该将应用程序拆分为模块,然后不要将服务保留在共享模块中 Do not specify app-wide singleton providers in a shared module. A lazy-loaded module that imports that shared module makes its own copy of the service. 我建议阅读此内容ARTICLE
  • 问题被标记为 Angular2 :) 感谢您的链接,今晚我会详细阅读。

标签: angular angular2-services


【解决方案1】:

仅仅几个月后,现在直接从角度指南中得到了答案。您可以使用以“app”开头的绝对路径从根目录引用模块。例如,如果您想加载共享模块,您只需使用此导入:

import { SharedModule } from 'app/shared/shared.module';

这里是指南中使用的:

https://angular.io/guide/ngmodule#app-routing

TypeScript 指南中也有关于此的部分:

https://www.typescriptlang.org/docs/handbook/module-resolution.html

【讨论】:

  • 已更新为import { componentName } from 'src/app/component'
【解决方案2】:

您可以使用一些允许您执行此操作的库。

如果您使用的是Webpack,请检查此answer,它将解决您的问题

Webpack 1

resolve: {
  root: [
    path.resolve(__dirname  + '/src')
  ]
}......

Webpack 2

resolve: {
  modules: [
    path.resolve(__dirname + '/src'),
    path.resolve(__dirname + '/node_modules')
  ]
}.....

之后就可以使用了

import configureStore from "store/configureStore";

而不是:

import configureStore from "../../store/configureStore";

如果你不使用 Webpack,你可以简单地安装 Babel Root Import

// Usually
import SomeExample from '../../../some/example.js';
const OtherExample = require('../../../other/example.js');

// With Babel-Root-Importer
import SomeExample from '~/some/example.js';
const OtherExample = require('~/other/example.js');

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多