React项目生产构建报错:Unexpected character '#' 问题求解
Great catch pinpointing the issue to npm-cli.js being bundled—its opening shebang line #!/usr/bin/env node is a Unix shell directive that webpack’s production loaders don’t recognize by default, triggering the error. Here are the most practical, clean solutions to resolve this:
1. Remove Accidental Imports of npm-cli.js
Start by checking your codebase for unintended references to npm’s internal tools. If you have lines like:
const npm = require('npm'); // or import 'npm';
These are pulling in npm-cli.js unnecessarily. Delete these imports immediately—your React app has no need to bundle npm itself.
2. Exclude npm-cli.js from Webpack Processing
If the file is being included via a third-party dependency, update your webpack.config.prod.js to explicitly exclude it from loader processing. Add a specific exclusion rule to your JavaScript loader:
module.exports = { // ... other production config settings module: { rules: [ { test: /\.js$/, exclude: [ /node_modules/, // Exclude the problematic npm-cli.js file specifically /node_modules\/npm\/lib\/npm-cli\.js/ ], use: 'babel-loader' // or your preferred JS transpiler } ] } };
This tells webpack to skip processing this file entirely, avoiding the unrecognized shebang line.
3. Use Shebang-Loader to Strip the Problematic Line
If you absolutely can’t exclude the file (a rare edge case), install shebang-loader to remove the shebang line during bundling:
First, install the loader:
npm install shebang-loader --save-dev
Then update your webpack rule to include it:
module.exports = { // ... other production config settings module: { rules: [ { test: /\.js$/, use: [ 'babel-loader', 'shebang-loader' // Strips the #! line from files ] } ] } };
Key Takeaway
The core issue is that npm-cli.js is a tool for npm’s internal use, not part of your React application. The cleanest fix is to ensure it never makes it into your bundle (solutions 1 or 2). Only use solution 3 if you have no other viable option.
内容的提问来源于stack exchange,提问作者Wouter Vanherck

