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-utils
在 node_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
对应的值
如何配置
那问题来了,我们该如何配置呢
- 配置环境变量
- 通过
shell
命令 - 重写
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/'
...
}
}
...