Webpack 4.5.0多页面构建配置优化及多服务器协作咨询
Hey Maxim, let's break down your questions one by one—this is a common scenario for multi-page apps, and I've got some solid workflows for Webpack 4.5.0 that'll cut down on repetitive config and get your dev server playing nice with Tornado.
Manually writing entries and HtmlWebpackPlugin instances for 10 pages is a recipe for repetitive, error-prone code. Instead, we'll dynamically generate configs from a single source of truth:
Step 1: Define a Page Config Array
Create an array that stores all metadata for your pages (entry points, HTML templates, required chunks, etc.). This is the only place you'll add new page details later:
const pages = [ { name: "home", entry: "./src/pages/home/index.js", template: "./src/pages/home/index.html", chunks: ["guestCommon", "vendors", "home"] // Map to your 3 entry chunks + page-specific chunk }, { name: "dashboard", entry: "./src/pages/dashboard/index.js", template: "./src/pages/dashboard/index.html", chunks: ["adminCommon", "vendors", "dashboard"] }, // Add the remaining 8 pages here ];
(Note: Your 3 "entry points" sound like chunked common code for different user types—guest, admin, user—so we reference them in the chunks array per page.)
Step 2: Dynamically Generate the entry Object
Combine your 3 common entries with page-specific entries using a reduce function:
const entry = { // Your 3 core common entries guestCommon: "./src/common/guest.js", userCommon: "./src/common/user.js", adminCommon: "./src/common/admin.js", // Dynamically add page entries ...pages.reduce((acc, page) => { acc[page.name] = page.entry; return acc; }, {}) };
Step 3: Dynamically Generate HtmlWebpackPlugin Instances
Loop through the pages array to create plugin instances instead of writing 10 manually:
const HtmlWebpackPlugin = require("html-webpack-plugin"); const htmlPlugins = pages.map(page => new HtmlWebpackPlugin({ filename: `${page.name}.html`, template: page.template, chunks: page.chunks, // Only load the chunks this page needs minify: process.env.NODE_ENV === "production" ? { collapseWhitespace: true, removeComments: true } : false }));
Then add htmlPlugins to your Webpack config's plugins array. Done—no more copy-pasting plugin code!
HtmlWebpackPlugin Instances? Nope—10 instances are exactly what you need (one per page). Each instance generates a single HTML file and specifies only the chunks required for that page (your relevant common entry + page-specific chunk + any shared vendor chunks).
You'd only need an 11th instance if you had an extra, unused page template—which you don't. The dynamic approach above ensures you never create more instances than necessary.
This is a bit niche, but two reliable proxy-based solutions will get them talking:
Option 1: Tornado Proxies Static Assets to webpack-dev-server
Use Tornado as your main server (handling API requests) and forward all static asset requests to webpack-dev-server (running on its default port 8080):
Add a proxy handler to your Tornado app:
import tornado.web import tornado.httpclient class StaticProxyHandler(tornado.web.RequestHandler): async def get(self, path): client = tornado.httpclient.AsyncHTTPClient() # Point to your running webpack-dev-server dev_server_url = f"http://localhost:8080/{path}" try: response = await client.fetch(dev_server_url) self.set_status(response.code) # Forward relevant headers (skip auto-managed ones like Content-Length) for header, value in response.headers.items(): if header not in ["Content-Length", "Transfer-Encoding"]: self.set_header(header, value) self.write(response.body) except tornado.httpclient.HTTPError as e: self.set_status(e.code) self.write(f"Static asset not found: {path}") # Update your Tornado routes application = tornado.web.Application([ # Your existing API routes (r"/api/(.*)", ApiHandler), # Proxy all static requests to webpack-dev-server (r"/static/(.*)", StaticProxyHandler), # Page routes (return HTML templates or redirect to webpack's HTML files) (r"/home", HomePageHandler), ])
In your Webpack config, set publicPath: "/static/" so generated assets use paths that trigger the proxy. Enable hot reloading with devServer: { hot: true, inline: true }.
Option 2: webpack-dev-server Proxies API Requests to Tornado
This is simpler—run webpack-dev-server as your main dev server, and forward API requests to Tornado (running on, say, port 8888):
Add this to your Webpack config's devServer section:
devServer: { port: 8080, hot: true, proxy: { "/api": { target: "http://localhost:8888", // Tornado's address changeOrigin: true, secure: false } } }
Now all frontend API calls to /api/... will automatically route to your Tornado server. You can access your pages directly via webpack-dev-server (e.g., http://localhost:8080/home.html).
内容的提问来源于stack exchange,提问作者Maxim Soltyk

