我无法使用 gulp 和 React 18 来制作包含所有内容的 index.html,未捕获的错误:缩小的 React 错误 #299

Edg*_*yan 2 reactjs gulp

在 React 18 发布之前,我一直是 React 和 gulp 的快乐用户。我创建了 React 应用程序并使用 gulp 将所有构建文件内容收集到 index.html 中。正如我所说,它适用于 18 之前的 React 版本。我在开发人员控制台中看到的错误是:

Uncaught Error: Minified React error #299; visit https://reactjs.org/docs/error-decoder.html?invariant=299 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    at n.createRoot ((index):6144:55)
    at (index):6952:27
    at (index):6953:23
    at (index):6954:15
Run Code Online (Sandbox Code Playgroud)

重现步骤,归功于Coding Shiksha:

  1. npx create-react-app sampleapp
  2. cd sampleapp
  3. npm install --save-dev gulp gulp-inline-source gulp-replace
  4. Ceate a .env file inside the root folder and copy paste the below code
INLINE_RUNTIME_CHUNK=false
GENERATE_SOURCEMAP=false
SKIP_PREFLIGHT_CHECK=true
Run Code Online (Sandbox Code Playgroud)
  1. create a gulpfile.js inside the root directory and copy paste the following code
const gulp = require('gulp');
const inlinesource = require('gulp-inline-source');
const replace = require('gulp-replace');

gulp.task('default', () => {
  return gulp
    .src('./build/*.html')
    .pipe(replace('.js"></script>', '.js" inline></script>'))
    .pipe(replace('rel="stylesheet">', 'rel="stylesheet" inline>'))
    .pipe(
      inlinesource({
        compress: false,
        ignore: ['png'],
      })
    )
    .pipe(gulp.dest('./build'));
});
Run Code Online (Sandbox Code Playgroud)
  1. npm run build
  2. npx gulp
  3. npm install -g serve
  4. serve -s build
  5. 打开浏览器 http://localhost:3000,打开开发控制台并观察错误

格式化(未缩小)的内容index.html发布在此处。

Tod*_*upa 7

我能够通过将 root.render 包装在 onload 监听器中来解决这个问题:

索引.js

document.addEventListener("DOMContentLoaded", (event) => {
  const root = ReactDOM.createRoot(document.getElementById("root"));
  root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
});  
Run Code Online (Sandbox Code Playgroud)