有没有办法在单个 html 文件中构建 React 应用程序? [英] is there a way to build a react app in a single html file?

查看:38
本文介绍了有没有办法在单个 html 文件中构建 React 应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个 React 应用程序,并将静态 css 和 js 文件有效地嵌入到我调用 yarn build 时生成的 index.html 中.

I want to build a react app and have the static css and js files effectively embedded into the index.html that gets produced when I call yarn build.

我显然可以破解输出并替换 <script src"...<link href="/static/css/... 标签内联版本,但希望有更优雅的解决方案.

I can obviously hack the output and replace the <script src"... and <link href="/static/css/... tags with inline versions but was hoping for a more elegant solution.

推荐答案

我搞定了.供将来参考(使用 react 16.7.0 & yarn 1.10.1)...

I got it working. For future reference (using react 16.7.0 & yarn 1.10.1)...

创建一个反应应用:

npx create-react-app my-app
cd my-app
yarn build

一切都好吗?酷,运行 eject 以便您可以访问 webpack 配置:

All good? Cool, run eject so that you have access to the webpack config:

yarn eject
rm -rf build node_modules
yarn install
yarn build

添加此项目并更新 webpack:

Add this project and update webpack:

yarn add html-webpack-plugin@4.0.0-beta.4
yarn add html-webpack-inline-source-plugin@1.0.0-beta.2

编辑config/webpack.config.js:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin'); <--- add this
...
plugins: [
  new HtmlWebpackPlugin(
    Object.assign(
      ...
      isEnvProduction
        ? {
            inlineSource: '.(js|css)$', <-- add this
            minify: {
              ...
  ),
  ...
  isEnvProduction &&
    shouldInlineRuntimeChunk &&
    new HtmlWebpackInlineSourcePlugin(HtmlWebpackPlugin), <--- add this
    new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime~.+[.]js/]),
    ...

运行 rm -rf build &&纱线构建&&serve -s build - 您加载的 index.html 现在应该包含内联的所有 js 和 css 内容.请注意,静态文件仍然在构建目录中创建,但页面不会使用它们.

Run rm -rf build && yarn build && serve -s build - the index.html you load should now contain all the js and css stuff inline. Note that the static files are still created in the build dir, but they aren't used by the page.

这篇关于有没有办法在单个 html 文件中构建 React 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆