0

I have the following code:

src/main.js

const importModule = async (moduleName) => {
  const mod = await import(moduleName);

  return mod;
};

const fs1 = await import("fs");
const fs2 = await importModule("fs");

When running node src/main.js, no problem.

Now, I bundle it with webpack with the following configuration:

webpack.config.js

import path from "path";
import { dirname } from "node:path";
import { fileURLToPath } from "node:url";

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

export default {
  mode: "development", 

  entry: "./src/main.js",

  target: "node",

  output: {
    path: path.resolve(__dirname, "dist"), 
    filename: "bundle.js",
    library: {
      type: "module",
    },
  },

  module: {
    rules: [
      {
        test: /\.js$/, 
        exclude: /node_modules/, 
        use: {
          loader: "babel-loader", 
        },
      },
    ],
  },

  experiments: {
    outputModule: true,
  },
};

And when running node dist/bundle.js I have the following error:

webpack://fs-import/./src/_lazy_referencedExports:__strict_namespace_object?:5 var e = new Error("Cannot find module '" + req + "'");
^ Error: Cannot find module 'fs' at eval (webpack://fs-import/./src/_lazy_referencedExports:__strict_namespace_object?:5:11) at async importModule (webpack://fs-import/./src/main.js?:4:15)
at async eval (webpack://fs-import/./src/main.js?:8:13) { code: 'MODULE_NOT_FOUND' } Node.js v20.19.5

Is there something I'm missing in the webpack configuration?

5
  • What is the reason for the existance of the importModule function? Based on what you've shown, it is a mere wrapper around import that adds nothing to it (except complexity). Commented Nov 5 at 9:46
  • Yeah this importModule function is kinda dummy in this example, but I want to experiment more complex import logics later. Commented Nov 5 at 9:52
  • Have you tried adding fs to your externals? Webpack then won't bundle fs, so any import("fs") or require("fs") just runs directly in Node. I believe it would look something like: externals: { fs: "commonjs fs" }. Commented Nov 5 at 10:25
  • 1
    I haven't got a solution and I'm not confident enough to say "you definitely can't" so this is not appropriate as an answer—though someone else is feel to post it—but I believe this is because Webpack tries to resolve all paths at compilation time & import(someVar) only works in some cases. Commented Nov 5 at 10:29
  • @ninadepina tried this with no more luck. RickN, it seems related to this effectively! Commented Nov 5 at 11:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.