简体   繁体   中英

How to bundle a Node TS/JS library with Webpack?

I have a Node project:

  • Codebase in Typescript
  • Bundled via Webpack and ts-loader
  • Target platform: Node.js
+-proj/
  +-src/
    |-file1.ts
    |-file2.ts
    |-file3.ts
    |-...
  |-package.json
  |-webpack.config.json
  |-tsconfig.json

This project is supposed to be a library. I need to build a bundle that in the end can be consumed by other Typescript projects targeting Node.

The problem

Any code consuming that final bundle will need to access only some classes I defined inside file1.ts and file2.ts . All other source files export stuff, but those are eventually referenced by those two files and I want the final library to expose only the components defined inside these two files.

// file1.ts

export class MyComponent1 {...}
export function myFunc() {...}
// file2.ts

import { MyComponent3 } from "./file3"

export class MyComponent2 {...}
export function myOtherFunc() {...}
// file3.ts

export class MyComponent3 {...}

Given the files above, the final bundle should expose MyComponent2 , MyComponent2 , myFunc and myOtherFunc .

Question

My problem is that I do not how to configure Webpack. It needs an entry point, but I need to expose many different things under src , how to do that?

Create a single file that would serve as the entry point. For example, it can be named main.ts or index.ts or anything you prefer.

The contents of the file would just re-exporting the contents of the files you want to be public:

export * from "./file1";
export * from "./file2";

If you want to export only some thing and not all from each file. Assuming file1 exports a , b , and c while file2 exports d , e , and f you can specify a subset like this:

export { a, b } from "./file1";
export { e, f } from "./file2";

Then you can configure Webpack to use your file in webpack.conf.js:

module.exports = {
    entry: "./src/main.ts", //or your choice of name
    /* ... */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM