[英]How to reuse webpack bundle in another bundle?
您好,我正在使用 SSR 構建一個 React 應用程序。 服務器和客戶端部分都寫在 typescript 中並分別進行編譯。 為了更好地理解這里的應用程序結構:
這里是服務器和客戶端包的簡化 webpack 配置:
// webpack.client.js
module.exports = {
mode: "development",
resolve: {
modules: ["src", "static", "node_modules"],
extensions: [".ts", ".tsx", ".js", ".jsx"],
},
entry: [
"./src/client/index.tsx"
],
output: {
filename: "bundle.js",
path: PUBLIC_PATH,
},
module: {
rules: [
{
test: /\.tsx?$/,
use: [
{
loader: "ts-loader",
}
],
},
]
},
plugins: [
new webpack.DefinePlugin({ IS_SERVER: false })
]
};
服務器配置看起來很像除了target
和externals
//webpack.server.js
const config = {
mode: "development",
resolve: {
modules: ["src", "static", "node_modules"],
extensions: [".ts", ".tsx", ".js", ".jsx"],
},
externals: [webpackNodeExternals()],
target: 'node',
entry: [
"./src/server/index.ts"
],
output: {
filename: "bundle.js",
path: SERVER_BUILD_PATH
},
module: {
rules: [
{
test: /\.tsx?$/,
use: [
{
loader: "ts-loader",
}
],
},
]
},
plugins: [
new webpack.DefinePlugin({ IS_SERVER: true })
]
};
在服務器代碼中,我得到了一個renderer
function,它將 React 應用程序渲染為字符串。
// renderer.tsx
import React from "react";
import { renderToString } from "react-dom/server";
import { App } from "client/App";
const html = (app) => `
<html>
<head>
</head>
<body>
<div id="root">${app}</div>
<script src="/public/bundle.js"></script>
</body>
</html>
`;
export async function renderer(req) {
const app = renderToString(<App />);
return html(app);
}
然后由快遞服務器返回給客戶端。
//index.ts
app.get("*", async (req, res) => {
const content = await renderer(req);
res.send(content);
});
如您所見,這兩個部分都需要轉譯 React 應用程序。 問題是 - 如何在服務器包中重用轉譯的客戶端代碼,以便服務器配置只需要轉譯index.ts
和renderer.tsx
?
您可以使用webpack-merge package 來做到這一點
這是我的例子
const merge = require('webpack-merge');
const baseConfig = require('./webpack.config.js');
const webpack = require("webpack");
module.exports = merge(baseConfig, {
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development'),
'BASE_URL': JSON.stringify('http://localhost:5000/')
}
})
],
watch: true
});
這可以使用resolve.alias
輕松完成: https://webpack.js.org/configuration/resolve/#resolvealias
只需將helpers
目錄在應用程序的目錄層次結構中向上移動並從中導入。
在你的情況下,我還想在你的應用程序的根級別使用單個webpack.config.js
文件重新設計應用程序,你可以在其中使用多編譯器功能組合客戶端和服務器配置並遵守原則“做不要重復自己“: https://stackoverflow.com/a/43689505/2569746
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.