Node.js生产环境启动Web应用报错排查求助
Let's break down what's happening here and fix this error step by step. The root issue is that Babel is accidentally compiling files inside your node_modules folder—specifically the convert-source-map module—even though you added an ignore rule. This leads to a compatibility problem with the SafeBuffer.Buffer API, causing the from method to be undefined.
Here are the most effective solutions:
1. Fix Your Babel Ignore Rule
Your current .babelrc ignore path is too vague. Let's make it more precise to ensure it catches all files under node_modules:
{ "presets": [ ["@babel/preset-env" , {"modules": "cjs"}], "@babel/preset-react" ], "plugins": [ "transform-class-properties" ], "ignore": [ "node_modules/**/*" ] }
The **/* wildcard ensures every file and subdirectory inside node_modules is ignored, which your original ./node_modules path might not have covered properly.
2. Force Ignore node_modules Directly in Your babel-node Command
Sometimes .babelrc rules don't play nice with babel-node in production. Add the --ignore flag directly to your start script in package.json to override this:
"start": "npm run clean && npm run compile && cross-env NODE_ENV=production babel-node --ignore 'node_modules/**/*' src/server/server.js --ignore ./src/client"
Make sure the --ignore argument comes before your entry file (src/server/server.js)—order matters here for babel-node.
3. Ditch babel-node for Production (Highly Recommended)
babel-node is designed for development—it compiles code on the fly, which is slow and unreliable in production. Instead, precompile your server code first, then run the compiled output:
- Add a new script to compile your server code in
package.json:
"compile-server": "babel src/server --out-dir dist/server --ignore 'src/client/**/*'"
- Update your
startscript to use the compiled files:
"start": "npm run clean && npm run compile && npm run compile-server && cross-env NODE_ENV=production node dist/server/server.js"
This eliminates the need for babel-node entirely, so there's no chance of it accidentally compiling node_modules files.
4. Check Your Node.js Version
The SafeBuffer.Buffer.from method was added in Node.js 6.0.0. If you're running an older version, upgrade to an LTS release (like 14.x or newer) to resolve this API compatibility issue.
5. Resolve Dependency Conflicts
If none of the above work, try updating or reinstalling your dependencies to fix any version mismatches:
# Update convert-source-map specifically npm update convert-source-map # Or do a clean install to reset all dependencies rm -rf node_modules package-lock.json npm install
Any of these steps should resolve the error. For production, I strongly recommend option 3—it's the most stable and performant approach.
内容的提问来源于stack exchange,提问作者José Carlos

