从应用程序包中排除本地 TypeScript 库

Exclude a local TypeScript library from application bundle

如何从为我的应用程序创建的包中排除本地 TypeScript 库?在我的用例中,我想为我的 TypeScript 库提供捆绑包,并为我的应用程序提供捆绑包作为单独的 JavaScript 文件。

我的图书馆

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' } ] }
};

我的申请

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' } ] }
};

在我的示例中,库代码包含在应用程序的捆绑包中。我希望该库 不包含 以便我可以将其作为单独的包提供。

使用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.

您想在 webpack 配置中添加 @mylib 作为外部库。

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

此外,Typescript 还需要库的类型。 所以你需要在类型文件中定义它们。 这是一个工作示例

typings.d.ts

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