I develop an app with node.js Fastify framework (typescript, ES syntax). I use Webpack to bundle the app and to compile typescript. The app bundles successfully, but when I try to run the resulting bundle.cjs file, I get the following error:
eferenceError: require is not defined in ES module scope, you can use import instead
at Object.events (file:///home/myzader/vc-app/backend/dist/bundle.mjs:601068:1)
at __webpack_require__ (file:///home/myzader/vc-app/backend/dist/bundle.mjs:613956:41)
at ./node_modules/pino/lib/proto.js (file:///home/myzader/vc-app/backend/dist/bundle.mjs:612505:26)
at __webpack_require__ (file:///home/myzader/vc-app/backend/dist/bundle.mjs:613956:41)
at ./node_modules/pino/pino.js (file:///home/myzader/vc-app/backend/dist/bundle.mjs:613549:15)
at __webpack_require__ (file:///home/myzader/vc-app/backend/dist/bundle.mjs:613956:41)
at ./node_modules/fastify/lib/logger.js (file:///home/myzader/vc-app/backend/dist/bundle.mjs:607600:14)
at __webpack_require__ (file:///home/myzader/vc-app/backend/dist/bundle.mjs:613956:41)
at ./node_modules/fastify/lib/reply.js (file:///home/myzader/vc-app/backend/dist/bundle.mjs:608101:21)
at __webpack_require__ (file:///home/myzader/vc-app/backend/dist/bundle.mjs:613956:41)
I tried to adjust the webpack configs. When I add some package to the externals array, it dooesn’t throw the error any more, but I geet the same error for another package from dependencies. I need a help definitely, Thank you!
const config = {
mode: 'development',
devtool: 'source-map',
entry: './app.ts',
target: 'node',
resolve: {
extensions: ['.ts', '.js', '.mjs'],
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.mjs', // Change the extension to .mjs
library: {
type: 'module' // Change the library type to 'module'
},
chunkFormat: 'module' // Change the chunk format to 'module'
},
experiments: {
outputModule: true
},
externals: [
nodeExternals({
allowlist: ['canvas', 'fastify', 'avvio', 'fastq', 'reusify', '@fastify/error', 'process-warning', 'abstract-logging', 'pino', 'pino-std-serializers', 'fast-redact', 'quick-format-unescaped']
})
],
module: {
rules: [{
test: /.(ts|js)$/, // Handle both .ts and .js files
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /.node$/, // Apply this rule to files ending in .node
loader: 'node-loader', // Use the node-loader for all .node files
},
],
},
stats: {
errorDetails: true, // Display details of errors
colors: true, // Output in colored format, useful in console
modules: true, // Display modules information
reasons: true, // Display the reason about why modules are included
warnings: true, // Display warnings
},
plugins: [
new webpack.ContextReplacementPlugin(
/awilix/, // The module that includes dynamic requires
(data) => {
delete data.dependencies[0].critical; // Remove the critical flag from these dependencies
return data;
}
),
],
};