【发布时间】:2020-02-25 20:49:05
【问题描述】:
这是一个奇怪的具体问题,我在任何地方都找不到任何信息。
我有一个主要的 React 应用程序,它可以动态加载其他 React 迷你应用程序。它通过组件的componentDidMount() 函数完成此操作,使用纯 JavaScript 在文档正文的末尾添加一个脚本标签,标签的 src 地址代理一个请求到 Web 服务器以返回单个捆绑文件,该文件是子- 应用程序加载。当组件被卸载时,脚本标签将从文档的主体中删除,并且 div 根被空白。
迷你应用程序需要在单个包中加载(无需在此处进入),我通过修改后的 npm run build 函数构建反应应用程序来实现这一点;
"scripts": {
"build": "npm run build:sass && npm run build:react && npm run build:bundle",
"build:react": "react-scripts build",
"build:bundle": "webpack --config webpack.config.js",
"build:sass": "node-sass --precision=5 --indent-type=space --output-style=nested --indent-width=2 src/styles/Site.scss src/styles/Site.css"
}
这个命令的 bundle 部分使用下面的 webpack.config.js 文件;
const path = require("path")
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
const glob = require("glob")
module.exports = {
entry: {
"bundle.js": glob.sync("build/static/?(js|css)/*.?(js|css)").map(f => path.resolve(__dirname, f)),
},
output: {
filename: "build/bundle.min.js"
},
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
plugins: [new UglifyJsPlugin()],
}
这反过来会生成一个单独的 bundle.min.js 文件,其中包含来自迷你应用程序的所有脚本、node_modules 和 css,主应用程序通过下面的组件加载这些文件。
export class MyComponent extends React.PureComponent<Props, object> {
componentDidMount() {
const script = document.createElement("script");
script.src = "myScriptSrc";
script.async = true;
script.id = this.AppIdToScriptId();
document.body.appendChild(script);
}
componentWillUnmount() {
document.getElementById("miniAppRoot").innerHTML = "";
if (this.props.app) {
document.getElementById(this.AppIdToScriptId()).remove();
}
}
AppIdToScriptId = () => "d" + this.props.App.Id.replace("-", "");
public render() {
return (<div id="miniAppRoot" ></div>);
}
}
export default MyComponent;
这一切都很好,我在这里遇到的唯一问题是通过 react mini-app 捆绑脚本加载的 css 即使在我删除了脚本标签并将 html 根目录空白后仍然存在。有谁知道为什么会这样?我不确定是否应该归咎于 webpack 配置、客户端缓存或任何其他数量的可能性,关于如何解决这个问题的任何想法?
【问题讨论】:
-
这对我来说似乎是浏览器缓存问题
-
就像你说的,它可以是任意数量的东西。您可以尝试将查询字符串附加到主 css 文件的末尾,以诱使浏览器重新绘制/重新加载样式。或者尝试将小程序显示设置为 display:none 和 display:
以强制浏览器重新绘制。另一种解决方法可能是通过对每个应用应用唯一的选择器来覆盖样式。 IE。 #mini-app-1 .your-common-class {...},#mini-app-2 .your-common-class {...}
标签: css reactjs typescript caching webpack