新手求助:如何在Express应用生成器的EJS项目中集成Webpack
Hey there! Let's get Webpack up and running with your Express + EJS setup. I'll break this down into simple, actionable steps so you can follow along even as a beginner.
Step 1: Install Required Dependencies
First, let's install Webpack and related tools. Open your terminal and run:
npm install webpack webpack-cli webpack-dev-middleware webpack-hot-middleware --save-dev
If you plan to process CSS or modern JavaScript (ES6+), install these additional loaders too:
npm install style-loader css-loader babel-loader @babel/core @babel/preset-env --save-dev
webpack-dev-middleware: Lets Express serve Webpack-generated files directly from memory (no need to write them to disk in dev mode)webpack-hot-middleware: Enables hot module replacement (auto-refresh your browser when code changes)- Loaders help Webpack process non-JS files like CSS or transpile modern JS to browser-compatible code
Step 2: Create Webpack Configuration File
Create a new file named webpack.config.js in your project root, and add this code:
const path = require('path'); const webpack = require('webpack'); module.exports = { // Entry point for your frontend code entry: [ './src/index.js', // Replace with your actual frontend entry file 'webpack-hot-middleware/client?reload=true' // Enable hot reloading ], // Output directory and filename for bundled files output: { path: path.join(__dirname, 'public/dist'), // We'll put bundled files in public/dist filename: 'bundle.js', publicPath: '/' // Match Express's static path }, mode: process.env.NODE_ENV === 'production' ? 'production' : 'development', module: { rules: [ // Process CSS files { test: /\.css$/, use: ['style-loader', 'css-loader'] }, // Transpile modern JS with Babel { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] }, plugins: [ new webpack.HotModuleReplacementPlugin() // Enable hot module replacement ] };
Make sure to create the src directory in your project root, and add an index.js file (your frontend entry point) and any CSS files you want to bundle.
Step 3: Update Your Express App (app.js)
Now let's modify your existing app.js to integrate Webpack. Here's the updated version with comments explaining changes:
var express = require('express'); var path = require('path'); var logger = require('morgan'); var index = require('./routes/index'); var app = express(); // --- Add Webpack integration starts here --- const webpack = require('webpack'); const webpackConfig = require('./webpack.config'); const compiler = webpack(webpackConfig); // Use webpack-dev-middleware in development mode if (process.env.NODE_ENV !== 'production') { app.use(require('webpack-dev-middleware')(compiler, { publicPath: webpackConfig.output.publicPath, stats: { colors: true } })); // Use webpack-hot-middleware for hot reloading app.use(require('webpack-hot-middleware')(compiler)); } // --- Webpack integration ends here --- // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // set path for static assets app.use(express.static(path.join(__dirname, 'public'))); // routes app.use('/', index); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('404 page.'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // render the error page res.status(err.status || 500); res.render('error', {status:err.status, message:err.message}); }); module.exports = app;
Step 4: Update Your EJS Template
Open your views/index.ejs file, and add the bundled Webpack file to the <head> or before the closing </body> tag:
<!DOCTYPE html> <html> <head> <title>Your Site</title> <!-- Include bundled CSS (if you're using CSS in your frontend code) --> <!-- <link rel="stylesheet" href="/bundle.css"> --> </head> <body> <h1>Hello from Express + EJS + Webpack!</h1> <!-- Include bundled JavaScript --> <script src="/bundle.js"></script> </body> </html>
Step 5: Add npm Scripts
Update your package.json to add scripts for building and running your app:
"scripts": { "start": "node ./bin/www", "dev": "NODE_ENV=development node ./bin/www", "build": "NODE_ENV=production webpack --mode production" }
- Run
npm run devto start your app in development mode with hot reloading - Run
npm run buildto create a production-ready bundle inpublic/dist - Run
npm startto start the app in production mode (uses the bundled files)
Quick Notes
- In development mode, Webpack serves files from memory, so you won't see the
bundle.jsinpublic/distuntil you runnpm run build - Make sure your frontend code (JS/CSS) is in the
srcdirectory so Webpack can process it - If you need to add more file types (like images), you can add additional loaders to the Webpack config (e.g.,
file-loader)
内容的提问来源于stack exchange,提问作者jomskris

