首页 > 解决方案 > 启用 Webpack HMR 时注入的模块未正确加载

问题描述

我正在开发一个库,然后使用 Webpack 将其注入到 html 文档中。我需要在项目上启用 HMR。但是,当我启用它时,库将无法正确加载。这是我从控制台得到的:

Library.init()不是函数。

并且库被加载为空object,而通过关闭 HMR,它被正确加载。

这是我的 Webpack 配置:

{ 
...baseConfigs,
entry: './src/index.ts',
output: {
        path: __dirname + '/dist',
        filename: `lib.js`,
        library: {
            name: 'Library',
            type: 'window',
        },
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'dist'),
        publicPath: '/',
        port: 8000,
        open: true,
        hot: true,
    },
    plugins: [
        ...baseConfig.plugins,
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, 'demo', 'index.html'),
            inject: 'head',
        }),
        new webpack.HotModuleReplacementPlugin(),
    ],
}

而入口点————index.ts是这样的:

import {main, subscribe} from './main' // Library's main functionality imported

export {
   init,
   subscribe,
}

if(module.hot){
   module.hot.accept('./index.ts')
}

我错过了一块拼图吗?

标签: javascriptwebpack

解决方案


推荐阅读