Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript module structure in JS with Webpack

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?

like image 852
Luis Aguilar Avatar asked Feb 08 '19 19:02

Luis Aguilar


People also ask

Can you use TypeScript with webpack?

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.

Does webpack include Node_modules?

webpack does not include node_modules dependency!!

Does webpack convert TypeScript to JavaScript?

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.

Does TS-loader use Tsconfig?

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.


1 Answers

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)

like image 71
Nicolas Gehlert Avatar answered Sep 18 '22 16:09

Nicolas Gehlert