typescript - 编译导出以供导入和窗口使用
问题描述
如何在打字稿中创建既可以从另一个模块导入又可以与<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()
}
我尝试了什么:
- 我不能
if
在.ts
文件中使用导出 - 我无法定义变量导出并使用自定义 if。
- 我尝试了不同
module
的tsconfig.json
:
我还认为我可以创建 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
。但与库大小相比,它有很多开销代码。
解决方案
您可以尝试使用模式汇总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}({});
推荐阅读
- javascript - addEventListener 是否添加或设置?
- css - 如何选择给定集合中的第 n 个元素
- android - 无法在 Windows 10 上安装 HAXM
- javascript - 试图在函数中创建多维数组
- python - Python - 骰子和硬币游戏
- python - 鉴于没有库或模拟,如何完全在 Amazon Athena 上测试我的 ETL 管道?
- javascript - 比较 Mongoose Doc 和 Express 当前日期中的日期
- python - 在python中分隔列CSV
- insert - Laravel 5.7 CRUD 解释
- database - 是否有可能使 mongoose 中的 MongoDB 成为像 Firebase 这样的实时数据库?