1

我正在使用Angular2-cli创建两个应用程序:MyFirstApp& MySecondApp。我希望MySecondApp导入MyFirstApp,以便我可以重用指令/服务/组件。当我 importMyFirstApp时,出现以下编译错误:Cannot find module 'MyFirstApp'.

以下是如何重现

    $ npm -v
    3.9.3

    $ node -v
    v6.2.1

    $ npm list  | grep 'angular'
    ├── @angular/common@2.0.0-rc.1
    ├── @angular/compiler@2.0.0-rc.1
    ├── @angular/core@2.0.0-rc.1
    ├── @angular/http@2.0.0-rc.1
    ├── @angular/platform-browser@2.0.0-rc.1
    ├── @angular/platform-browser-dynamic@2.0.0-rc.1
    ├── @angular/router@2.0.0-rc.1
    ├─┬ angular-cli@1.0.0-beta.5

    $ ng new MyFirstApp
    $ cd MyFirstApp
    $ ng g service MyFirstAppService
    $ ng build
    $ cd ..
    $ ng new MySecondApp
    $ cd MySecondApp
    $ npm install ../MyFirstApp --save #Also tried w/ ng install ../MyFirstApp and github link
    $ vim src/app/my-second-app.component.ts

修改src/app/my-second-app.component.ts为如下所示:

import { Component } from '@angular/core';
import { MyFirstAppService } from 'MyFirstApp';

@Component({
  moduleId: module.id,
  selector: 'MySecondApp',
  templateUrl: 'mysecondapp.component.html',
  styleUrls: ['mysecondapp.component.css']
})
export class MySecondAppAppComponent {
  title = 'MySecondApp works!';
}

我尝试了许多版本的import { MyFirstAppService } from 'MyFirstApp';(ie import { MyFirstAppServiceService } from './../../node_modules/my-first-app/src/app/my-first-app-service.service'; & co) 并玩了system-config.ts(使用thisthis ) 没有任何运气。我总是有一个Cannot find module 'MyFirstApp'.

有什么建议么 ?

编辑:通过如下调整system-config.ts(第 1 到 14 行):

const map: any = {
  'my-first-app': 'vendor/my-first-app/app/index.js'
};

/** User packages configuration. */
const packages: any = {
  'my-first-app': {
    format: 'cjs'
  }
};

我能做到import { MyFirstAppServiceService } from 'my-first-app/src/app/my-first-app-service.service';.../dist/...不起作用。但这似乎不是正确的方法……难道不应该这样做import { MyFirstAppServiceService } from 'my-first-app/my-first-app-service.service'吗?

请注意,生成的vendors/my-first-app/目录不包含MyFirstApp

$ # While in MySecondApp
$ tree dist/vendor/my-first-app 
dist/vendor/my-first-app
├── angular-cli-build.js
└── config
    ├── environment.js
    ├── karma.conf.js
    ├── karma-test-shim.js
    └── protractor.conf.js

谢谢。

4

2 回答 2

0

在您的 src/app/mysecondapp.component.ts 中,尝试替换:

import { MyFirstAppService } from 'MyFirstApp';

这样

import { MyFirstAppService } from './app/MyFirstApp';

我希望它会工作:)

于 2016-06-14T22:05:08.290 回答
0

Angular2-cli 项目的开发人员希望在 1.0.0 版本中支持库/插件风格的项目

现在,我们可以做些什么来让它发挥作用:

  1. 在库 package.json 中添加一个 main
  2. npm install yourlib --save 在您的其他应用程序中
  3. 配置您的第二个应用程序,以便它根据您的需要打包您的库。gulp 的一个例子:

    var copyScripts = require('ionic-gulp-scripts-copy');

    gulp.task('assets', function(){
      return copyScripts({src:'node_modules/your-lib/dist/**/*', dest:'our-dest'});
    });
    
于 2016-06-23T20:12:37.157 回答