【问题标题】:Classes is not in the build unless they are instantiated类不在构建中,除非它们被实例化
【发布时间】:2018-09-04 10:56:09
【问题描述】:

我正在为一些简单的组件编写一个小型库来学习一些TypeScript,但是在未显式实例化类时构建库时出现问题。

我希望能够使用字符串来实例化一个类。在定义一个类之后,我将类名和构造函数添加到一个对象。

/**
 * Component class store
 */
let classes: { [key: string]: IConstructable<IComponent> } = {};

export function addToDynamic(cls: IConstructable<IComponent>) {
    classes[cls.name] = cls;
}

/**
 * A component
 */
export class Container extends BaseComponent implements IComponent {
    items: object[];

    constructor() {
        super();
    }
}

addToDynamic(Container);

以下代码不起作用,因为Container 未实例化:

import { Container } from './gui/container';
import { DynamicClass } from './gui/base';

let c2:Container = new DynamicClass('Container') as Container;
c2.add(document.body);

不过,这将在构建中包含 Container

import { Container } from './gui/container';
import { DynamicClass } from './gui/base';

let c1:Container = new Container();
let c2:Container = new DynamicClass('Container') as Container;
c2.add(document.body);

我的webpack.config.js

const path = require('path');

module.exports = {
    mode: 'development',
    entry: './src/index.ts',
    devtool: 'inline-source-map',
    devServer: {
        contentBase: './dist'
    },
    module: {
        rules: [
        {
            test: /\.tsx?$/,
            use: 'ts-loader',
            exclude: /node_modules/
        }]
    },
    resolve: {
        extensions: [ '.ts', '.js' ]
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        library: 'sugar-ant-lib',
        libraryTarget: 'umd'
    }
};

问题是如何包含src中的所有文件?

更新

将下面的行添加到我的index.ts 会将文件添加到构建中。

import './gui/container';

我还发现它可能与tripple-slash directives 有关,但我还不知道。

【问题讨论】:

    标签: typescript webpack


    【解决方案1】:

    Webpack 通过递归识别文件中的 import 或 require 关键字来创建依赖关系图。如果有任何文件没有在你的项目的任何地方导入,webpack 找不到它。这将通过删除构建中未使用的文件来提供优势

    一种解决方案是在任何文件上显式添加 import 语句,因此 web pack 也会将其添加到依赖关系图中。

    另一种解决方案是动态导入,将文件动态导入代码最适合的位置,文件名将是动态的。所以 webpack 会根据名字创建一个模块。

    https://medium.com/front-end-hacking/webpack-and-dynamic-imports-doing-it-right-72549ff49234

    更多关于依赖图

    https://webpack.js.org/concepts/dependency-graph/

    【讨论】:

      猜你喜欢
      • 2019-01-06
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      相关资源
      最近更新 更多