我正在为一些简单的组件编写一个小型库,以学习一些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';另外,我发现这可能与三重斜杠指令有关,但我还不知道。
发布于 2018-09-03 19:21:41
Webpack通过识别导入或递归地从您的文件中要求关键字来创建依赖关系图。如果在您的项目中没有导入任何文件,webpack将找不到。这将通过删除生成中未使用的文件来提供优势。
一种解决方案是在任何文件上显式地添加导入语句,所以web也会将其添加到依赖关系图中。
另一种解决方案是动态导入,在最适合的代码中动态导入文件,文件名将是动态的。因此,web将根据名称创建一个模块。
https://medium.com/front-end-hacking/webpack-and-dynamic-imports-doing-it-right-72549ff49234
更多关于依赖关系图的信息
https://stackoverflow.com/questions/52152617
复制相似问题