Recently delving into the world of TypeScript, I find myself struggling to grasp how to create a TypeScript library that can be utilized in another TypeScript module through webpack.
This particular library is meant to be functional within a browser environment.
At present, my project structure and build output look like this:
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
└── tsconfig.json
Configuration for 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 contents:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"sourceMap": true,
"outDir":"out",
"declaration": true
},
"exclude": [
"node_modules",
"bower_components",
"typings/global",
"build"
]
}
Example of Foo.ts:
export class Foo{
foo(){}
}
Bar.ts code snippet:
import {Foo} from './Foo'
export class Bar{
public foo:Foo = new Foo();
}
The resulting build output includes:
- A webpack bundle
- TypeScript declarations for each file
Now, here are some questions that arose:
- How do I import/consume this library via bower in another browser application(using TypeScript and webpack)?
- What import syntax should be used in an application that consumes this library(e.g.
import .. from
orrequire
)? - Is it possible that using webpack for bundling the library may not be necessary at all?
UPDATE: Following @basarat's suggestion, I switched to NPM for managing local dependencies between TypeScript modules instead of using bower, and everything worked smoothly.