Christian Fritz
Christian Fritz

Reputation: 21354

Webpack on the backend: missing exports

I'm trying to use webpack on the backend to transpile this code (called sub.js):

export const foo1 = () => {
  console.log("I'm foo1");
};

console.log('loaded');

I can compile it and then import it fine. On import (require) I see the 'loaded', but the imported object is empty and in particular has no function foo1.

This is my webpack.config.js:

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: `./sub.js`,
  module: {
    rules: [{
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      options: {
        plugins: [
          '@babel/plugin-proposal-class-properties'
        ]
      },
    }],
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'backend.js'
  },
  mode: 'production',
};

My package.json:

{
  "name": "sub",
  "version": "1.0.0",
  "description": "",
  "main": "dist/backend.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.13.8",
    "@babel/plugin-proposal-class-properties": "^7.13.0",
    "@babel/preset-env": "^7.13.9",
    "@babel/preset-react": "^7.12.10",
    "babel-loader": "^8.2.2",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1"
  }
}

I test using:

> npx webpack && node --eval "r = require('./dist/backend.js'); console.log(r);"
asset backend.js 45 bytes [emitted] [minimized] (name: main)
runtime modules 396 bytes 2 modules
./sub.js 204 bytes [built] [code generated]
webpack 5.65.0 compiled successfully in 250 ms
loaded
{}

I was expecting to see:

loaded
{foo1: [Function]}

or similar.

Upvotes: 2

Views: 1091

Answers (1)

Christian Fritz
Christian Fritz

Reputation: 21354

Found the issue. Apparently you need to explicitly declare exported libraries in the output. Now that I've added this:

  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'backend.js',
    library: {
        type: 'commonjs-module',
    },
  },

I get:

> npx webpack && node --eval "r = require('./dist/backend.js'); console.log(r);"
asset backend.js 192 bytes [emitted] [minimized] (name: main)
./sub.js 323 bytes [built] [code generated]
webpack 5.65.0 compiled successfully in 275 ms
loaded
{ foo1: [Function] }

as expected.

For reference https://webpack.js.org/configuration/output/#outputlibrary.

Upvotes: 2

Related Questions