gpt4 book ai didi

typescript - 捆绑和使用 webpack 构建的 typescript 库的正确方法?

转载 作者:搜寻专家 更新时间:2023-10-30 22:06:57 24 4
gpt4 key购买 nike

我最近开始使用 typescript,但无法理解如何使用 webpack 构建将在另一个 typescript 模块中使用的 typescript 库。

还有这个库,旨在在浏览器中运行。

目前我得到了以下结构和构建输出:

lib
├── build
│   ├── typings // tsc output with declaration:true
│   │   ├── Bar.d.ts
│   │   └── Foo.d.ts
│   └── lib.bundle.js //webpack bundle file
├── src
│   ├── Bar.ts
│   └── Foo.ts
├── bower.json
├── package.json
└── tconfig.json

webpack 配置:

webpackOptions = {
resolve: { extensions: ['', '.ts'] },
module: {
loaders: [{ test: /\.ts$/, exclude: [/node_modules/,/out/,/.*\.d\.ts/],include:[/\.ts$/], loaders: ['ts-loader']}]
},
ts:{
compilerOptions:compilerOptions
},
output: {
library:"mylib",
libraryTarget:'commonjs',
filename: 'mylib.bundle.js'
}
}

tsconfig.json:

{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"sourceMap": true,
"outDir":"out",
"declaration": true
},
"exclude": [
"node_modules",
"bower_components",
"typings/global",
"build"
]
}

Foo.ts为例:

export class Foo{
foo(){}
}

Bar.ts:

import {Foo} from './Foo'
export class Bar{
public foo:Foo = new Foo();
}

所以我有以下构建输出:

  • webpack 包
  • 每个文件的 typescript 声明

问题是:

  • 我如何在另一个浏览器应用程序中通过 bower 导入/使用这个库(它也将使用带有 webpack 的 typescript)?
  • 在使用此库的应用程序中将使用哪种导入语法(例如 import .. fromrequire )?
  • 也许我根本不应该使用 webpack 来打包库?

更新:按照@basarat 的建议,在没有 bower 的情况下使用 NPM 管理 typescript 模块之间的本地依赖关系,并且一切正常

最佳答案

Maybe I shouldn't use webpack for bundling library at all

这是我推荐的。将捆绑留给顶级应用程序消费者。

例如这是一个模块 csx https://github.com/basarat/csx你可以在 typescript 中使用。您可以看到它没有以任何特殊方式捆绑。它只是一个节点模块。如果人们想在浏览器中使用它捆绑就在他们身上 🌹

更多

https://basarat.gitbooks.io/typescript/content/docs/quick/nodejs.html

关于typescript - 捆绑和使用 webpack 构建的 typescript 库的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38211068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com