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?
importModulefunction? Based on what you've shown, it is a mere wrapper aroundimportthat adds nothing to it (except complexity).importModulefunction is kinda dummy in this example, but I want to experiment more complex import logics later.fsto your externals? Webpack then won't bundlefs, so anyimport("fs")orrequire("fs")just runs directly in Node. I believe it would look something like:externals: { fs: "commonjs fs" }.import(someVar)only works in some cases.