I'm trying to publish a TypeScript library using webpack and with a folder structure like:
src/
module1/
some-class.ts
index.ts
module2/
some-other-class.ts
index.ts
etc/
If used in TS, I should be able to do:
import { SomeClass } from 'my-library/module1';
And when using require, should be able to do:
const SomeClass = require('my-library/module1');
Webpack needs an entry (or multiple entries) and outs files matching those entries. However, I see defining entries for every nested folder very impractical, and also don't know how to make deep nested entries like require('my-library/module1/submodule1/etc')
.
Also, authored that way, it might not follow the dts files outputted by the ts-loader
.
What am I missing here? Is there a way to make webpack replicate the module structure of the TS sources?
Am I using the wrong tool?
If so, what do people use to bundle libraries?
Either webpack directly compiles TypeScript files into the bundle, with the help of the loader ts-loader . Or we compile the TypeScript files ourselves, to Javascript files in the directory dist/ (like we did in the previous chpater). Then webpack doesn't need a loader and only bundles JavaScript files.
webpack does not include node_modules dependency!!
Like Babel, Webpack depends on TSC to transpile TypeScript to JavaScript but as TSC doesn't have a clue about Webpack, hence Webpack needs a loader to talk to TSC. This is where the ts-loader comes into play. Webpack compiles a TypeScript file using ts-loader package which asks TSC to do the compilation.
ts-loader uses tsc , the TypeScript compiler, and relies on your tsconfig. json configuration. Make sure to avoid setting module to "CommonJS", or webpack won't be able to tree-shake your code.
I think you can just create an index.ts file in your toplevel src/ directory and export every subfolder from there, for example export * from 'module1';
And when you create a new module you simply need to add the a new line to export the proper directory.
On a side note, if you want to export something from your top level that is actually deeper inside a module you can use the following syntax export { myFunc } from './module1/nested/myFunc';
In that case your use can require('myLibrary/myFunc')
instead of require('myLibrary/module1/nested/myFunc')
Edit: As pointed out by @Dehli those index files are called Barrels (https://basarat.gitbooks.io/typescript/docs/tips/barrel.html)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With