Typescript 编译导出以供导入和窗口使用

Typescript 编译导出以供导入和窗口使用,typescript,tsconfig,Typescript,Tsconfig,如何在typescript中创建既可以从另一个模块导入又可以与一起使用的文件。例如: index.ts: tsconfig.json: 如何生成这样的输出: class A { echo() { console.log('a'); } } if (typeof exports !== 'undefined) { Object.defineProperty(exports, "__esModule", { value: true }); exports.A

如何在typescript中创建既可以从另一个模块导入又可以与一起使用的文件。例如:

index.ts:

tsconfig.json:

如何生成这样的输出:

class A { 
   echo() {
      console.log('a');
   }
}
if (typeof exports !== 'undefined) {
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.A = A;
// don't expose to global scope if module is imported via webpack or etc
} else if (typeof window !== 'undefined') {
    window.A = A
}
我还希望我的编译器使用以下命令生成index.d.ts:

我尝试了什么:

我无法在if in.ts文件中使用导出 我不能定义变量导出并使用自定义if。 我在tsconfig.json中尝试了不同的模块: 我还认为我可以创建2个tsconfig并运行2次tsc。但是当我的index.ts包含export时,如果没有导出方法,我就无法生成js文件。例如,当模块=无时,它仍会生成

 Object.defineProperty(exports, "__esModule", { value: true });` 
我得到

exports is not defined
我看到atm的唯一方法是添加webpack并创建一个单独的文件main.js,该文件包含导入语句和窗口分配。但与库大小相比,它有很多开销代码。

您可以尝试使用iLife模式:

$npm i汇总类型脚本汇总插件类型脚本汇总插件uglify $./node_modules/.bin/rollup-c rollup.config.js rollup.config.js:

index.ts:

output browser.js:

var myBundle=functiono{use strict;var n=t.prototype.echo=function{console.loga},t;function t{}返回o.A=n,o};
checkout@DanielPérez我生成的目标不重要,webpack会增加很多开销,无论是var还是assign,只要你使用webpack,它都会添加代码我有一个单独的文件库,我不需要webpack中的依赖项管理汇总怎么样,rollup main.js-format umd-name myBundle-file bundle.js所以我首先通过ts编译器运行它@DanielPérez那么我应该指定什么格式?如果我指定umd,它要求umd依赖项在全局范围内。如果我指定iife,它不会从源代码中删除导出,它所做的只是将源代码包装在匿名函数中
export declare class A {
   echo()
}
 Object.defineProperty(exports, "__esModule", { value: true });` 
exports is not defined
import typescript from 'rollup-plugin-typescript';
import { uglify } from "rollup-plugin-uglify";

export default {
    input: './index.ts',
    output: {file: './browser.js', format: 'iife', name: 'myBundle'},
    plugins: [
        typescript(),
        uglify()
    ]
}
// index.ts
export class A {
  echo() {
    console.log("a");
  }
}