【问题标题】:Why webpack returns an empty object when requiring its output?为什么 webpack 在需要它的输出时返回一个空对象?
【发布时间】:2019-01-30 07:00:11
【问题描述】:

我正在尝试捆绑我的项目,然后需要捆绑的缩小输出。
我的 index.js 文件如下所示:

const browserHost = require('./hosts/browserHost')
const workerHost = require('./hosts/workerHost')
module.exports = {
    initBrowserHost: options => browserHost.init(options),
    initWorkerHost: options => workerHost.init(options)
}

当需要它时,我有两个初始化函数。当我将我的项目与webpack 捆绑并需要index.min.js 时,我有一个空对象。
Webpack 配置:

const TerserPlugin = require('terser-webpack-plugin')
const path = require('path')

module.exports = {
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: [
                    /node_modules/,
                    /\.unit\.js$/
                ],
                use: ['babel-loader']
            }
        ]
    },
    node: {
        fs: 'empty',
        dns: 'empty'
    },
    target: 'node',
    entry: [
        './src/index.js'
    ],
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'index.min.js'
    },
    optimization: {
        minimizer: [
            new TerserPlugin({
                parallel: true,
                terserOptions: {
                    ecma: 6
                }
            })
        ]
    }
}

我做错了什么?

【问题讨论】:

  • 你看生成的文件了吗?也许禁用缩小。
  • 您在哪里需要 index.js,在它所依赖的模块之一中?
  • @Bergi 不,我在测试和其他存储库(npm 模块)中需要它
  • 你解决过这个问题吗?
  • @RobertMolina 嘿,我刚刚删除了所有内容,目前首先运行babel,然后在生成的文件上运行 webpack。 .webpack.config 仅使用 modeentryoutput 属性。有效,但我仍然不明白为什么它不能那样工作^

标签: javascript webpack ecmascript-6


【解决方案1】:

如果你从 node_modules 构建一个库供其他人使用,你需要告诉 webpack 你想要支持umd(简单来说,你想让你的消费者从require(yinon_lib) 使用它或者 import ..来自“yinon_lib”)。

这样做的方法是:

output: {
      ...
      libraryTarget: 'umd', 
    },

更多信息:

例子:

https://github.com/stavalfi/lerna-yarn-workspaces-example/tree/master/packages/x-core

【讨论】:

    猜你喜欢
    • 2016-11-12
    • 2019-10-29
    • 2014-12-14
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2018-02-23
    相关资源
    最近更新 更多