如何使用 create-react-app 从 webpack 中的捆绑文件路径、publicPath、PUBLIC_URL 中删除初始斜杠?
我们如何从 webpack 中自动包含在 index.html
中的所有文件中删除初始斜杠(例如
如何在命令行 npx create-react-app
创建的 React 项目中自定义 webpack.config.js
而不弹出它?
How can we remove the initial slash from all the files included automatically in index.html
from webpack (like <script src="/static/js/...">
...) and all the paths of a react app?
How is possible to customize the webpack.config.js
in a react project created by the command line npx create-react-app
without ejecting it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Fancesco Orsi 的回答的第 1 部分解决了我的部分问题,但
/static/
似乎需要搞乱配置或添加库。将在我的反应和电子构建之间运行的后记搞砸在一起更简单。我相信人们可以根据他们的需要重新利用它。
我使用以下代码创建了一个 JavaScript 文件,并将
package.json
中的后脚本指向它。"postbuild": "node mid-build.js"
不太优雅,但它有效,我可以返回调试构建。
Part 1 of Fancesco Orsi's answer fixed part of my problem, but the
/static/
appears to require messing with configs or adding libraries.It was simpler to botch together a postscript that runs between my react and electron build. I'm sure people could repurpose this for what they need.
I made a JavaScript file with the following code and pointed a post-script in
package.json
to it."postbuild": "node mid-build.js"
Not elegant, but it works and I can get back to debugging builds.
打开
public/index.html
删除%PUBLIC_URL%
之后/之前的所有斜杠,例如,
则变为
如果您使用变量
process.env.PUBLIC_URL
, > 在 jsx 中,始终删除变量前后的斜杠。例如,
:
在项目的根目录中创建一个名为
.env
的空文件,输入以下文本替换
webpack.config.js
的publicPath
值(您通常可以在/node_modules/react-scripts/config/webpack.config.js 中找到此文件
)而不触及原始(不推荐!!),您可以使用像react-app-rewired
或craco
这样的库>。下面您可以看到 craco 的示例 https://www.npmjs.com/package/@ craco/craco :
通过
npm i @craco/craco
安装后,您需要将
package.json
中的一些行从 替换之后
为
,在您的根项目添加一个名为
craco.config.js
在文件内的
添加以下代码即可
open the
public/index.html
removing all the slashes after/before%PUBLIC_URL%
for example
become
if you use the variable
process.env.PUBLIC_URL
in your jsx, remove always the slash after/before the variable.for example
become
Create a empty file in the root of the project called
.env
entering this text:to replace the
publicPath
value of thewebpack.config.js
(you normally find this file in/node_modules/react-scripts/config/webpack.config.js
) without touching the original (it is not recommended!!) you can use a library likereact-app-rewired
orcraco
.Below you can see an example with craco https://www.npmjs.com/package/@craco/craco :
After the installation by
npm i @craco/craco
you need to replace some lines of your
package.json
from
to
after that, in your root project add a file called
craco.config.js
inside the file add the following code
that's it