Martin
Martin

Reputation: 726

Exclude a local TypeScript library from application bundle

How can I exclude a local TypeScript library from the bundle that is created for my application? In my use case, I want to provide the bundle for my TypeScript library and the bundle for my application as separate JavaScript files.

My Library

index.ts

export class Greeter {
    public greet(): void {
        console.log("Hello World"); 
    }
}

package.json

{
    "private": true,
    "devDependencies": {
        "typescript": "3.1.1",
        "ts-loader": "5.2.1",
        "webpack": "4.20.2",
        "webpack-cli": "3.1.2"
    },
    "scripts": {
        "start": "webpack"
    }
}

tsconfig.json

{
    "compilerOptions": {
        "module": "es6",
        "target": "es5"
    }
}

webpack.config.js

module.exports = {
    entry: './src/index.ts',
    resolve: { extensions: [".js", ".ts"] },
    output: { filename: 'bundle.js', library: '@mylib', libraryTarget: 'umd' },
    module: { rules: [ { test: /\.ts$/, use: 'ts-loader' } ] }
};

My Application

index.ts

import {Greeter} from "@mylib/index";

new Greeter().greet();

package.json

{
    "private": true,
    "devDependencies": {
        "typescript": "3.1.1",
        "tsconfig-paths-webpack-plugin": "3.2.0",
        "ts-loader": "5.2.1",
        "webpack": "4.20.2",
        "webpack-cli": "3.1.2"
    },
    "scripts": {
        "start": "webpack"
    }
}

tsconfig.json

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": { "@mylib/*": ["../mylib/src/*"] },
        "module": "es6",
        "target": "es5"
    }
}

webpack.config.js

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
    entry: './src/index.ts',
    resolve: { extensions: [".ts", "js"], plugins: [new TsconfigPathsPlugin({})] },
    output: { filename: 'bundle.js' },
    module: { rules: [ { test: /\.ts$/, use: 'ts-loader' } ] }
};

In my example, the library code is included in the bundle of the application. I would like that the library will be not included so that I can provide it as a separate bundle.

Upvotes: 0

Views: 2835

Answers (1)

lukas-reineke
lukas-reineke

Reputation: 3322

Use externals

The externals configuration option provides a way of excluding dependencies from the output bundles. Instead, the created bundle relies on that dependency to be present in the consumer's environment. This feature is typically most useful to library developers, however there are a variety of applications for it.

You want to ad @mylib as an external library in the webpack config.

externals : {
  '@mylib': 'mylib',
},

In addition, Typescript also needs the typings for the library. So you need to define them in a typings file. This is a working example

typings.d.ts

declare module '@mylib' {
    export class Greeter {
        greet();
    }
}

Upvotes: 1

Related Questions