我的方法确实有效,但我错过了这两个脚本:
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
所以对于本地测试来说是:
<div id="react-reporting"></div>
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="http://localhost:3000/static/js/bundle.js"></script><script src="http://localhost:3000/static/js/0.chunk.js"></script>
<script src="http://localhost:3000/static/js/main.chunk.js"></script>
我还遇到了有关 sockjs 的错误,该错误是由导入 React 应用程序的测试文件引起的,该文件是作为 file:// 打开的,而不是通过 http:// 打开的
Edit
经过更多测试后,我发现使用 webpack 是最好的解决方案 - 它使应用程序可以作为单个文件进行访问。
包.json
...
"scripts": {
"start": "webpack-dev-server --inline --hot",
"build": "webpack --config webpack.config.js"
},
...
webpack.config.js
const path = require("path")
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
const glob = require("glob")
module.exports = {
entry: ['@babel/polyfill','./src/index.js'],
output: {
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
],
},
optimization: {
minimizer: [new UglifyJsPlugin()]
}
}
- 需要 polyfill 才能与 IE11 兼容
- 每个处理的文件(从条目开始)都算作模块。如果它与规则的“测试”部分匹配,则应用该规则(排除除外)。
.babelrc
{
"presets": ['@babel/react',
['@babel/preset-env', {
"targets": {
"browsers": ["last 2 versions", "ie >= 11"]
}
}]],
"plugins": ['@babel/plugin-proposal-class-properties']
}
- 仅需要plugin-proposal-class-properties,因为我在类中有一些静态成员。
跑步时
npm start
Webpack-Dev-Server 将启动并使应用程序可以在http://localhost:8080/dist/bundle.js http://localhost:8080/dist/bundle.js.
将应用程序嵌入到另一个站点的代码:
<div id="react-reporting"></div>
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="http://localhost:8080/dist/bundle.js"></script>