create-react-app 创建项目 homepage 配置主机名不生效

本文解析了配置homepage遇到的问题及解决办法,详细介绍了通过配置环境变量、使用shell命令或重写publicPath来实现正确设置的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

homepage 配置主机名不生效

背景

最近一个项目上想把打包出来的文件带上服务器的地址,如下:
在这里插入图片描述

但是配置了 "homepage": "http://jspace-fe.wwwcom/" 一直不生效,why?

为什么不生效

通过 eject,产看 cli 本身的 webpack ,在 webpack.config.js 中看到配置如下:

const paths = require('./paths');
output: {
    ...
    publicPath: paths.publicUrlOrPath,
    ... 
}

接下来我们看下 paths文件

const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath');

const publicUrlOrPath = getPublicUrlOrPath(
  process.env.NODE_ENV === 'development',
  require(resolveApp('package.json')).homepage,
  process.env.PUBLIC_URL
);

接下来看下 react-dev-utils/getPublicUrlOrPath 这个方法做了什么,注意:react-dev-utilsnode_modules下,设计到的主要内容如下

function getPublicUrlOrPath(isEnvDevelopment, homepage, envPublicUrl) {
  const stubDomain = 'https://create-react-app.dev';

  ...

  if (homepage) {
    // strip last slash if exists
    homepage = homepage.endsWith('/') ? homepage : homepage + '/';

    // validate if `homepage` is a URL or path like and use just pathname
    const validHomepagePathname = new URL(homepage, stubDomain).pathname;
    return isEnvDevelopment
      ? homepage.startsWith('.')
        ? '/'
        : validHomepagePathname
      : // Some apps do not use client-side routing with pushState.
      // For these, "homepage" can be set to "." to enable relative asset paths.
      homepage.startsWith('.')
      ? homepage
      : validHomepagePathname;
  }

  return '/';
}

这个函数里面有个需要注意的地方就是 const url = new URL(url [, base])
在这里插入图片描述

所以代码里面的 const validHomepagePathname = new URL(homepage, stubDomain).pathname; 中的 new URL(homepage, stubDomain)就是 new URL('http://jspace-fe.www.com/','https://create-react-app.dev')它的返回值是http://jspace-fe.www.com/,但是这个返回值取得是 pathname
会返回/
在这里插入图片描述

所以最终并不会返回 homepage 对应的值

在这里插入图片描述

如何配置

那问题来了,我们该如何配置呢

  1. 配置环境变量
  2. 通过 shell 命令
  3. 重写 publicPath
配置环境变量

先说第一种,配置环境变量,就是在 根目录 下新建一个 .env 的文件,里面内容如下:

PUBLIC_URL = http://jspace-fe.www.com/
shell 命令
"build": "PUBLIC_URL=http://jspace-fe.www.com/ craco build",
重写publicPath

craco.config.js 文件中

...
configure: {
    output: {
        ...
        publicPath: 'http://jspace-fe.www.com/'
        ... 
    }
}
...
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值