以前的答案不起作用,因为作者不再支持html-webpack-inline-source-plugin,取而代之的是官方插件html-inline-script-webpack-plugin和html-inline-css-webpack-plugin。以下方法适用于截至 2021 年 10 月的最新 React 17。步骤:
创建一个 React 应用程序
create-react-app my-app
cd my-app
yarn
yarn start
确保它正常工作,您对输出感到满意。然后,弹出你的配置(我认为这可以在不弹出配置的情况下完成,但我懒得去查找如何配置 CRA)
yarn eject
rm -rf build node_modules
yarn
yarn build
然后,添加 Webpack 插件(假设您想要在这里嵌入 CSS 和脚本,如果您只想要另一个,只需删除一个)
yarn add html-inline-css-webpack-plugin -D
yarn add html-inline-script-webpack-plugin -D
最后,将这些添加到 Webpack 配置 config/webpack.config.js。首先在文件顶部声明它们:
const HTMLInlineCSSWebpackPlugin = require('html-inline-css-webpack-plugin').default;
const HtmlInlineScriptPlugin = require('html-inline-script-webpack-plugin');
然后将它们添加到plugins: [...] 集合中。搜索 new InlineChunkHtmlPlugin 并在之后添加它们:
isEnvProduction &&
shouldInlineRuntimeChunk &&
new HTMLInlineCSSWebpackPlugin(),
isEnvProduction &&
shouldInlineRuntimeChunk &&
new HtmlInlineScriptPlugin(),
注意:包含isEnvProduction / shouldInlineRuntimeChunk 检查很重要!如果您跳过这些,则在运行yarn start 时热刷新将不起作用。您只想在生产模式下嵌入脚本,而不是在开发期间。
现在,如果您运行yarn build,您会发现所有嵌入在build/index.html 中的CSS 和JS。如果你运行yarn start,它将启动一个热重载的开发环境,你可以在其中进行开发。