复现React开发环境配置时npm run dev编译未生成bundle.js问题
Hey there, let's figure out why your npm run dev isn't generating that bundle.js file!
The issue here is pretty straightforward: the command you're running (nodemon --exec babel-node src/server.js) is only meant to run your Node.js server with Babel transpilation—it doesn't handle bundling your React frontend code into a bundle.js file at all. That's why you see the compile step but no bundle output.
Here's how to fix this step by step:
First, set up a bundler (we'll use Webpack, the most common choice for React projects):
Install the necessary dev dependencies:npm install webpack webpack-cli babel-loader @babel/core @babel/preset-react @babel/preset-env --save-devNext, create a
webpack.config.jsfile in your project root with this basic configuration (adjust paths to match your project structure):module.exports = { // Point to your React app's entry file (e.g., where you render your root component) entry: './src/client/index.js', // Define where Webpack should output the bundled file output: { path: __dirname + '/public', filename: 'bundle.js' }, // Configure Babel to transpile React and modern JS module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-react', '@babel/preset-env'] } } } ] }, mode: 'development' };Update your
package.jsonscripts to run both the server and the bundler (we'll useconcurrentlyto run them in parallel):
First installconcurrently:npm install concurrently --save-devThen modify your scripts section:
"scripts": { "dev": "concurrently \"nodemon --exec babel-node src/server.js\" \"webpack --watch\"", "build": "webpack --mode production" }The
webpack --watchflag tells Webpack to watch for changes in your frontend files and recompilebundle.jsautomatically, whileconcurrentlylets you run the server and bundler at the same time.Finally, make sure your HTML file (e.g.,
public/index.html) includes a script tag pointing to the generatedbundle.js:<script src="/bundle.js"></script>Also, double-check that your server (in
src/server.js) is serving thepublicdirectory as static files. If you're using Express, add this line:app.use(express.static('public'));
Now when you run npm run dev, you'll see both your server starting up and Webpack generating/updating bundle.js in your public folder whenever you make changes to your React code.
内容的提问来源于stack exchange,提问作者Pedro Miguel Pimienta Morales

