如何在NPM上正确发布用TypeScript编写的Angular 1.5模块?

时间:2016-08-15 10:08:12

标签: angularjs intellij-idea typescript npm webpack

我正在尝试发布一个NPM模块,以便在另一个项目中使用Webpack。该模块使用TypeScript编写,包含一个Angular 1.5模块。到目前为止,我已经想到了这样的事情:

import {ExampleDirective} from './example/ExampleDirective';
import {ExampleComponent} from './example/ExampleComponent';
import {IExampleInterface} from './example/IExampleInterface';
import {ExampleFilter} from './utils/ExampleFilter';
import {ExampleClass} from './example/ExampleClass';
import {ExampleService} from './example/ExampleService';

// export everything that you want to access directly in TS code outside the package
export {
    IExampleInterface, ExampleClass, ExampleService
}

// add to the module everything that should be available via Angular DI mechanism
angular.module('my.components', [])
    .directive('example1', ExampleDirective.factory())
    .component('example2', new ExampleComponent())
    .filter('example3', ExampleFilter.filter)
    .service('ExampleService', ExampleService);

上面的文件称为index.ts,并导入/导出要使用的所有TS代码。然后我得到了以下package.json:

{
  "name": "my-components",
  "version": "0.0.6",
  "main": "lib/index.ts",
  "typings": "lib/index",
  "files": [
    "lib/"
  ],
  "scripts": {
    "prepublish": "typings install && tsc"
  },
  "dependencies": {
    "angular": "1.5.*",
    "lodash": "4.13.*",
    "moment": "2.14.*"
  },
  "peerDependencies": {
    "bootstrap": "3.3.*",
    "font-awesome": "4.6.*"
  },
  "devDependencies": {
    "typescript": "1.8.*",
    "typings": "1.3.*"
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "ES5",
    "module": "commonjs",
    "emitDecoratorMetadata": true,
    "declaration": true,
    "outDir": "lib"
  },
  "files": [
    "src/index.ts",
    "typings/index.d.ts"
  ]
}

和typings.json:

{
  "globalDependencies": {
    "angular": "github:DefinitelyTyped/DefinitelyTyped/angularjs/angular.d.ts#060060dc34ef700a6ea9e00ccee69b570ff3c242",
    "lodash": "github:DefinitelyTyped/DefinitelyTyped/lodash/lodash.d.ts#83f954972eea14a29161a0d9b9e602c4f8f824d1",
    "moment": "github:DefinitelyTyped/DefinitelyTyped/moment/moment.d.ts#56295f5058cac7ae458540423c50ac2dcf9fc711",
    "moment-node": "github:DefinitelyTyped/DefinitelyTyped/moment/moment-node.d.ts#8886ae591751e8a8237fa855617745768f0b1bdf"
  }
}

当我运行npm发布时,所有内容都是从/ src文件夹编译的,JS代码和TS定义根据需要位于/ lib文件夹中。发布后,我可以在我的HTML模板中使用指令和组件并注入服务。

但是有一个问题:当我需要在任何地方导入我的TS定义时,我需要像这样导入它:

import {ExampleClass, IExampleInterface, ExampleService} from 'my-components/lib/index';

而不是例如:

import {ExampleClass, IExampleInterface, ExampleService} from MyComponents;

这不是什么大问题,但它使代码编写更难,因为我的IDE(IntelliJ Ultimate)无法弄清楚自动导入。如何修改index.ts文件以便于导入?我无法在NPM / TypeScript / typings / Webpack文档中找到任何提示或约定。非常感谢。

0 个答案:

没有答案