javascript - 需要带有 npm 和 typescript 的自定义模块

标签 javascript node.js npm typescript

让我们玩两个项目:main-projectlib-project它们都是用typescript编写的,然后使用gulp编译到常见的 javascript。
我们的目标是在 main-project 中需要 lib-project

lib-project

|-- package.json
|-- gulpfile.js
|-- dist
   |-- index.js
   |-- a.js
| src
   |-- index.ts
   |-- a.ts

我们已经创建了那些从 ts 编译它们的 js;让我们快速浏览一下它们(我们有索引,因为我们最终需要这么多导出)

index.ts

import a = require('./a');
module.exports = {A: a.A};

a.ts

export class A {
  field: string;
  constructor(aField: string) {this.field = aField;}
  toString() : string {return `A: ${this.field}`;}
}

index.js

var a = require('./a');
module.exports = { A: a.A };

a.js

var A = (function () {
    function A(aField) {
        this.field = aField;
    }
    A.prototype.toString = function () {
        return "A: " + this.field;
    };
    return A;
})();
exports.A = A;
<小时/>

这就是介绍;现在,我将其推送到 git 存储库,并要求它作为 package.json 中的依赖项,并运行 npm install,我们的主项目是:

主项目

|-- package.json
|-- gulpfile.js
|-- node_modules
    |--lib-project
       |-- dist
         |-- index.js
         |-- a.js
    |--node
       |...
 |--src
    |--app.ts

app.ts 中失败:找不到模块 lib-project

app.ts

import a = require('lib-project');
var foo = new a.A('HELLO');
console.log(foo.toString());
<小时/>

我尝试了什么?

  1. 将lib项目的index.js移动到根文件夹
  2. 在 package.json 中,设置字段 "main": "dist/index.js"
  3. 导入 a = require('node_modules/lib-project/dist/index');
  4. 导入 a = require('../node_modules/lib-project/dist/index');
  5. 多个版本的 tsc( typescript 编译器)

感谢任何帮助:)

<小时/>

编辑

package.json

{
  "name": "lib-project",
  "version": "0.1.0",
  "description": "description here",
  "main": "dist/index.js",
  "scripts": {},
  "author": "",
  "license": "MIT",
  "dependencies": {
  }
}

最佳答案

我相信您缺少的是 lib 项目根目录中的 lib-project.d.ts 文件。这将填补您在index.ts中已有的 Angular 色,但您需要稍微调整它来填补这个 Angular 色

|-- package.json
|-- gulpfile.js
|-- lib-project.d.ts <-- formerly index.ts
|-- dist
   |-- a.js
| src
   |-- a.ts

lib-project.d.ts 看起来像这样:

declare module 'lib-project' {
  import a = require('./a');
  export = {A: a.A};
}

然后在使用这个时你可以使用:

import {A} from 'lib-project';

您可以引用我在这里所做的导出:https://github.com/Brocco/ng-bridge

也导入:https://github.com/Brocco/ng-bridge-samples/blob/master/app/app.ts#L1

关于javascript - 需要带有 npm 和 typescript 的自定义模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32222010/

相关文章:

Node.js mocha 进程 (_mocha) 不会在 CTRL-C 时退出

javascript - Chrome 的executeScript 函数不起作用

javascript - textarea onload 中的示例文本

javascript - Vue.js v-show 和 v-else 没有按预期工作?

node.js - ENOTEMPTY 目录不为空,rmdir : npm-react-popper-tooltip

node.js - eslint --fix 在 npm 运行时不起作用

javascript - 在 Angular 中设计模型

javascript - 当调用 'this' 的函数位于子对象的对象内部时,您将如何引用 'this'?

javascript - 问题导入 polymer 元素

node.js - npm install : Use global package if it exists, 而不是安装两次