GroovyPanda
GroovyPanda

Reputation: 3842

Webpack library build returns undefined when imported

Just sharing a problem and solution I spent hours on debugging:

I have a codebase that I want to build as a library with webpack, and include in another project. However, when I import the output file in the other library, it returns undefined.

This is the (simplified) webpack config:

{
  entry: './index.js',
  mode: 'development',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app/my-app.[name].js'
    library: 'my-app',
    libraryTarget: 'umd'
  },
  optimization: {
    runtimeChunk: 'single',
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendors: {
          name: 'vendors',
          test: /[\\/](node_modules|libraries)[\\/]/
        }
      }
    },
    minimizer: [new TerserPlugin({
      cache: true,
      sourceMap: true,
      parallel: true,
      exclude: [/my-app.vendors.js/]
    })]
  },
}

From the other project, I would import the library as follows:

const lib = require('./lib/my-app/dist/my-app.main');
console.log(lib);

Without any errors on the page, the console would simply show undefined.

Upvotes: 2

Views: 1662

Answers (1)

GroovyPanda
GroovyPanda

Reputation: 3842

Turns out the solution was simple: since I'm using splitChunks, the output consists of 3 files: my-app.runtime.js, my-app.vendors.js and my-app.main.js. I assumed each chunk would require its necessary dependencies automatically, but I assumed wrong. To make the library work, I needed to import like this:

require('./lib/my-app/dist/my-app.runtime');
require('./lib/my-app/dist/my-app.vendors');
const lib = require('./lib/my-app/dist/my-app.main');
console.log(lib);

The other is important, since main will need vendors and runtime.

Quite obvious if you think about it, but maybe this will help someone else who happens to miss it. The lack of errors in the console does not help the debugging.

Upvotes: 4

Related Questions