首页 > 解决方案 > 编译导出以供导入和窗口使用

问题描述

如何在打字稿中创建既可以从另一个模块导入又可以与<script src=""/>. 例如:

索引.ts

export class A {

   echo() {
     console.log('a');
   }
}

tsconfig.json

{
  "compilerOptions": {
    "lib": ["es2017", "dom"],
    "target": "es5",
    "module": "commonjs",
  },
}

如何生成这样的输出:

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

export declare class A {
   echo()
}

我尝试了什么:

我还认为我可以创建 2 个 tsconfig 并运行 tsc 2 次。index.ts但是当我的contains时,我无法生成没有某种导出方法的 js 文件export。例如,"module"="none"它仍然会生成

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

我得到

exports is not defined

我看到 atm 的唯一方法是添加 webpack 并创建一个main.js具有 import 语句和分配的单独文件window。但与库大小相比,它有很多开销代码。

标签: typescripttsconfig

解决方案


您可以尝试使用模式汇总iife

$ npm i rollup typescript rollup-plugin-typescript rollup-plugin-uglify
$ ./node_modules/.bin/rollup -c rollup.config.js

rollup.config.js

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()
    ]
}

索引.ts

// index.ts
export class A {
  echo() {
    console.log("a");
  }
}

输出browser.js

var myBundle=function(o){"use strict";var n=(t.prototype.echo=function(){console.log("a")},t);function t(){}return o.A=n,o}({});


推荐阅读