Dynamic require of "path" is not supported
im trying to build and run express server code
entry/server.js:
import express from 'express'
const app = express()
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000, () => {
console.log(`Example app listening on http://localhost:3000`)
})
entry/build.js:
import * as esbuild from 'esbuild'
await esbuild.build({
entryPoints: [
'entry/server.js',
],
bundle: true,
outdir: 'private',
platform: 'node',
format: 'esm',
})
package.json:
{
"name": "bas-framework-2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "node entry/build.js",
"serve": "node private/server.js",
"dev": "npm run build && npm run serve"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module",
"devDependencies": {
"esbuild": "^0.19.2",
"express": "^4.18.2"
}
}
when i do npm run dev i get this error:
file:///Users/jdion84/Sites/bas-framework-2/private/server.js:12
throw Error('Dynamic require of "' + x + '" is not supported');
^
Error: Dynamic require of "path" is not supported
at file:///Users/jdion84/Sites/bas-framework-2/private/server.js:12:9
at node_modules/depd/index.js (file:///Users/jdion84/Sites/bas-framework-2/private/server.js:37:20)
at __require2 (file:///Users/jdion84/Sites/bas-framework-2/private/server.js:15:50)
at node_modules/body-parser/index.js (file:///Users/jdion84/Sites/bas-framework-2/private/server.js:16528:21)
at __require2 (file:///Users/jdion84/Sites/bas-framework-2/private/server.js:15:50)
at node_modules/express/lib/express.js (file:///Users/jdion84/Sites/bas-framework-2/private/server.js:21855:22)
at __require2 (file:///Users/jdion84/Sites/bas-framework-2/private/server.js:15:50)
at node_modules/express/index.js (file:///Users/jdion84/Sites/bas-framework-2/private/server.js:21924:22)
at __require2 (file:///Users/jdion84/Sites/bas-framework-2/private/server.js:15:50)
at file:///Users/jdion84/Sites/bas-framework-2/private/server.js:21929:30
Node.js v20.4.0
This issue is already tracked here: https://github.com/evanw/esbuild/issues/1921
In summary, this runtime error is caused by bundling CJS libraries into ESM context (i.e. bundle express in format: 'esm'). esbuild uses closures to wrap these CJS liraries, and Node.js forbids dynamic (i.e. not at the top level) require on builtin modules.
I would still suggest you to exclude these dependencies from your bundle with --packages=external or --external:express since your runtime supports loading them from the file system, and it also bundles less code.
@hyrious will work if i deploy the code?
@hyrious will work if i deploy the code?
It depends on your deployment environment, if you are only sending the build output upstream then no - it won't. If you are sending the whole application root up, including any modules and all the other files needed to produce the build; then it should work fine :)