环境:前端react18+webpack5+typescript
背景:支持前端框架本地联调测试及嵌入spring boot thymeleaf 框架发布前端站点,为支持区分灰度正常站点静态资源获取问题
创建public/start.html文件用于本地调试启动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
修改paths.js
// config after eject: we're in ./config/
module.exports = {
...
appHtml: resolveApp('public/index.html'),
startHtml: resolveApp('public/start.html'),
...
};
修改webpack.config.js
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(
Object.assign(
{},
isEnvProduction
{
inject: false,
template: paths.appHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: {
template: paths.startHtml,
}
)
),
修改script/start.js
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.startHtml, paths.appIndexJs])) {
process.exit(1);
}
修改public/index.html
<!DOCTYPE html>
///有这一行springboot执行时才能解析 thymeleaf MVC模板
<html lang="en" xmlns:th="[http://www.thymeleaf.org](http://www.thymeleaf.org/)">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app" />
<title></title>
<!-- 获取springboot MVC传参值,并挂载到window属性下 -->
<script th:inline="javascript">
let bodyData = {
staticPath: [[${ staticPath }]],
ajaxPath: [[${ ajaxPath }]],
};
let bindToGlobal = (obj, key) => {
if (typeof window[key] === 'undefined') {
window[key] = {};
}
for (let i in obj) {
window[key][i] = obj[i] === null "" : obj[i]
}
};
bindToGlobal(bodyData, 'bodyData');
</script>
<!-- 打包重写html文件时,动态添加springbootMVC变量写法 -->
<% Array.isArray(htmlWebpackPlugin.files.js) && htmlWebpackPlugin.files.js.forEach(function(file){ %>
<script defer="defer" th:attrprepend="src=@{${staticPath}}+@{<%= file %>}"></script>
<% }) %>
<% Array.isArray(htmlWebpackPlugin.files.css) && htmlWebpackPlugin.files.css.forEach(function(file){ %>
<link th:attrprepend="href=@{${staticPath}}+@{<%= file %>}" rel="stylesheet" />
<% }) %>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
typescript ,修改react-app-env.d.ts
declare interface Window {
bodyData: any
}