简体   繁体   中英

Why webpack returns an empty object when requiring its output?

I'm trying to bundle my project and then require the bundled minified output.
My index.js file looks like this:

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

When requiring it I have my two init functions. When I'm bundling my project with webpack and requiring index.min.js , I have an empty object.
Webpack config:

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
                }
            })
        ]
    }
}

What am I doing wrong?

In case you build a library for others to use from node_modules, you need to tell webpack that you want to support umd (in simple words, you want to let your consumers use it from require(yinon_lib) or import .. from 'yinon_lib'`).

The way to do that is:

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

More information:

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM