Cannot locally import a module I bundled with webpack 5

Viewed 34

I am trying to bundle a library with Webpack 5 and import it in a separate package. However, it fails with the error message SyntaxError: The requested module 'test-module' does not provide an export named 'default', and if I try to do a named import, I get SyntaxError: The requested module 'test-module' does not provide an export named 'log'.

I will supply my files here, but first, this is my file structure:

|- test/
|  |- src/
|  |  |- index.js
|  |- package.json
|  |- webpack.config.js
|- src/
|  |- index.js
|  |- package.json

Essentially, the test/ folder contains the library source and the distribution bundled code. Whilst the src/ folder is the one that is trying to import the bundled library.

test/package.json:

{
  "name": "test-module",
  "type": "module",
  "module": "lib/bundle.js",
  "version": "0.0.1",
  "description": "",
  "main": "lib/bundle.js",
  "author": "",
  "license": "ISC",
  "scripts": {
    "build": "webpack --config webpack.config.js"
  },
  "devDependencies": {
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0"
  }
}

test/webpack.config.js:

import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export default {
  mode: 'production',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'lib'),
    filename: 'bundle.js',
    library: {
      name: 'log',
      type: 'umd',
      umdNamedDefine: true,
      export: 'default'
    },
    clean: true
  }
};

test/src/index.js:

export function log(param) {
  console.log(param)
}

export default log;

When I run npm run build, it successfully builds:

|- test/
|  |- lib/
|  |  |- bundle.js

However, I cannot seem to work out how to 'access' my exported function, which is how I get my errors. Here are the files where I try to import and use the library function:

src/package.json:

{
  "name": "test-src",
  "type": "module",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "test-module": "file:../test"
  }
}

src/index.js:

import log from 'test-module'
log('hi')

And when I run npm start, that's when I get the error SyntaxError: The requested module 'test-module' does not provide an export named 'default'. How can I ensure that the function is properly exported in my bundle so that it can be imported by my other package?

0 Answers
Related