커스텀 PUBLIC_URL로 create-react-app 프로젝트를 빌드할 수 없습니다.
난 노력하고 있어.
PUBLIC_URL=http://example.com npm run build
최신 create-module-script를 사용하여 구축한 프로젝트입니다.
「」, 「」의 은,%PUBLIC_URL%
public/index.html
치 '는 빈 입니다.PUBLIC_URL
.
public/index.html
<script src="%PUBLIC_URL%/static/js/jarvis.widget.min.js"></script>
인터넷 검색과 스택오버플로우를 몇 시간 동안 보면, 다음과 같은 정보가 거의 쓰여지지 않았습니다.PUBLIC_URL
GitHub의 create-react-app.
제가 뭘 잘못하고 있는지 조언해 주실 분 있나요?
'하다'도homepage
package.json
후npm run build
하다
The project was built assuming it is hosted at the server root.
To override this, specify the homepage in your package.json.
For example, add this to build it for GitHub Pages:
"homepage" : "http://myname.github.io/myapp",
중 하나로 .package.json
{
// ...
"scripts": {
// ...
},
"homepage": "https://example.com"
}
있는 는, homepage
★★★★★★★★★★★★★★★★★」PUBLIC_URL
대신 다음과 같은 메시지가 나타납니다.
The project was built assuming it is hosted at https://example.com.
You can control this with the homepage field in your package.json.
나 같은 사람은 다음과 같은 기능을 찾고 있습니다.
<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">
후, 「」를 설정합니다.https://dsomething.cloudfront.net
로로 합니다.homepage
package.json
동작하지 않습니다.
1. 퀵솔루션
하다
표시)
set PUBLIC_URL=https://dsomething.cloudfront.net&&npm run build
(linux/mac)
PUBLIC_URL=https://dsomething.cloudfront.net npm run build
그리고 당신은 얻을 것이다.
<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">
를 참조해 주세요.
2. 영속적이고 권장되는 솔루션
하다라는 을 만들어 보세요..env
이 있다존손
에는 다음과 같이
PUBLIC_URL=https://dsomething.cloudfront.net
평소와같이 build평 ( 소소((( )npm run build
)
지수
<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">
3. 이상한 해결책 (최신 리액트 스크립트 버전에서는 동작하지 않습니다)
것것son jj jjj.
.cloudfront.net ".cloudfront.net",
다음으로 index.html이 생성됩니다.
<script type="text/javascript" src="//dsomething.cloudfront.net/static/js/main.ec7f8972.js">
이는 기본적으로 다음과 같습니다.
<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">
제가 알기로는
PUBLIC_URL 변수는 이렇게 사용되지 않습니다.매뉴얼에 따르면 HTML에서 PUBLIC_URL을 사용할 수 있습니다.
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
또는 JavaScript:
render() {
// Note: this is an escape hatch and should be used sparingly!
// Normally we recommend using `import` for getting asset URLs
// as described in “Adding Images and Fonts” above this section.
return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
}
PUBLIC_URL은 사용자가 원하는 값으로 설정할 수 없습니다.Webpack 빌드 시스템 이외의 전개에 파일을 저장하는 방법입니다.
하려면 , 하고, 을 CRA 에 합니다.src/index.js
삭제:
console.log('public url: ', process.env.PUBLIC_URL)
이미 존재하는 URL이 표시됩니다.
자세한 내용은 CRA 문서를 참조하십시오.
실제로 환경변수를 설정하는 방법은 운영체제마다 다릅니다.
Windows (cmd.exe)
set PUBLIC_URL=http://xxxx.com&&npm start
(주의: 공백 부족은 의도적인 것입니다.)
Linux, macOS(Bash)
PUBLIC_URL=http://xxxx.com npm start
권장:
{
"scripts": {
"serve": "cross-env PUBLIC_URL=http://xxxx.com npm start"
}
}
참조: 마스터 / facebook incubator / create - contract - app / README.md#adding-temporary-environment-variables-in-your-shell
문서를 참조하십시오.PUBLIC_URL을 선택하는 .env 파일을 사용할 수 있습니다.
그 용도는 기억하셔야 합니다만...
이 변수를 사용하여 자산을 지정한 URL(호스트명 포함)로 말 그대로 참조할 수 있습니다.이것은, CDN 를 사용해 애플리케이션을 호스트 하는 경우에 특히 도움이 됩니다.
'소스코드'가 있는지 합니다.process.env.NODE_ENV === 'development'
true
호스트 URL은 자동으로 삭제되고 경로만 반환됩니다.
예를 들어 다음과 같이 설정하면
PUBLIC_URL=http://example.com/static/
하다.http://example.com
되는 것은 「」입니다./static
.
, 루트 은 ""과 같이만 되므로 "URL"은 "URL"로 설정합니다.http://example.com
URL 문자열에는 서브패스가 없기 때문에 빈 문자열만 반환됩니다.
되는 은 '아까', '아까', '아까', '아까', '아까', '아까', '아까'라고 전화를 걸었을 때 입니다.react-scripts start
「」를 참조해 주세요.react-scripts build
isEnvDevelopment
되다false
http://example.com
에서 .env
filename을 클릭합니다.
다음은 getPublicUrlOrPath.js의 소스 코드입니다.
/**
* Returns a URL or a path with slash at the end
* In production can be URL, abolute path, relative path
* In development always will be an absolute path
* In development can use `path` module functions for operations
*
* @param {boolean} isEnvDevelopment
* @param {(string|undefined)} homepage a valid url or pathname
* @param {(string|undefined)} envPublicUrl a valid url or pathname
* @returns {string}
*/
function getPublicUrlOrPath(isEnvDevelopment, homepage, envPublicUrl) {
const stubDomain = 'https://create-react-app.dev';
if (envPublicUrl) {
// ensure last slash exists
envPublicUrl = envPublicUrl.endsWith('/')
? envPublicUrl
: envPublicUrl + '/';
// validate if `envPublicUrl` is a URL or path like
// `stubDomain` is ignored if `envPublicUrl` contains a domain
const validPublicUrl = new URL(envPublicUrl, stubDomain);
return isEnvDevelopment
? envPublicUrl.startsWith('.')
? '/'
: validPublicUrl.pathname
: // Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
envPublicUrl;
}
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 '/';
}
여기서 설명하는 바와 같이 create-react-app은 다음 문자로 시작하는 환경 변수만 가져옵니다.REACT_APP_
'이러다'는PUBLIC_URL
@@redbmk는 @redbmk에서 온 으로 생각됩니다.homepage
의 package.json
filename을 클릭합니다.
왜 설정을 할 수 없는지 모르겠네요.출처에서,PUBLIC_URL
homepage
const envPublicUrl = process.env.PUBLIC_URL;
...
const getPublicUrl = appPackageJson =>
envPublicUrl || require(appPackageJson).homepage;
코드에 중단점을 설정하여 환경 변수를 재정의하는 논리를 확인할 수 있습니다.
이 문제는 github 페이지에서 리액트 앱을 호스팅하려고 하면 명백해집니다.
내가 이걸 어떻게 고쳤는지
에는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★app.tsx
라우터를 포함합니다.기본 이름을 설정했습니다.<BrowserRouter basename="/Seans-TypeScript-ReactJS-Redux-Boilerplate/">
상대적인 URL이므로 로컬로 실행 및 호스트 기능을 완전히 단순화할 수 있습니다.기본 이름 값은 GitHub의 저장소 제목과 일치합니다.이것은 GitHub 페이지가 자동으로 생성하는 경로입니다.
그게 내가 해야 할 전부였다.
다음 사이트에서 GitHub 페이지에 호스트되는 작업 예를 참조하십시오.
https://sean-bradley.github.io/Seans-TypeScript-ReactJS-Redux-Boilerplate/
이 솔루션은 Linux bash 명령줄에서 작동합니다.
- 리액트 프로젝트 루트 디렉토리로 이동합니다.
- 해당 디렉토리의 bash 터미널을 엽니다.
- 그 후, 다음의 2개의 명령어를 실행하면
PUBLIC_URL
변경:
> export PUBLIC_URL=https://example.com
> npm run build
이 경우,PUBLIC_URL
환경변수는 영향을 주지 않습니다.이 문제가 원인일 수 있습니다.PUBLIC_URL
무시당하다.create-react-app 버전 3.4.0에서 수정되었습니다.
앱에 라우팅 기능이 있는 경우 다음과 같이 시도해 보십시오.
프로젝트 루트에 .env라는 파일을 만듭니다.여기서 package는 다음과 같습니다.json을 찾을 수 있습니다.다음과 같이 프로덕션 URL을 추가해 주세요.
PUBLIC_URL=https://something.com
루트 설정에서 BrowserRouter에 basename을 추가합니다(App.js/App.jsx에서).
<BrowserRouter basename="https://something.com">
우선 리액트 컴파일 코드는 "순수 자바 스크립트"입니다.따라서 html 페이지에서 다음과 같은 방법으로 이 코드를 참조할 수 있습니다.
< script src="my_compiled_component.js" >< /script >
리액트 컴포넌트 작성은 메인 웹사이트 하이퍼링크에 의존해서는 안 됩니다.리액트 코드에서 컴포넌트가 실행되고 있는 웹 사이트를 찾으려면 다음과 같은 방법을 사용합니다.
window.location.protocol + '//'+ window.location.hostname + ':' + window.location.port
이 패턴에 따라서는 모든 사용자가 HTML 호출을 통해 컴포넌트를 찾을 수 있도록 일부 폴더에는 변경 권한이 필요할 수 있음을 이해하는 것이 중요합니다.컴파일된 리액트 코드를 배치하는 방법을 정의하려면 어떻게 해야 합니까?이것은, 수동에서 이 출력을 설정할 수 있는 Web pack등의 것을 사용하는 것으로 실시할 수 있습니다.
언급URL : https://stackoverflow.com/questions/42686149/cant-build-create-react-app-project-with-custom-public-url
'sourcecode' 카테고리의 다른 글
Ajax 요청을 사용하여 브라우저에서 다운로드 (0) | 2023.02.15 |
---|---|
URL에서 해시 제거 (0) | 2023.02.15 |
최대 날짜로 레코드 가져오기 (0) | 2023.02.15 |
@Autowired in kotlin과 같은 봄 주석 사용법 (0) | 2023.02.15 |
도커 컨테이너의 WordPress(연락처 양식)에서 이메일을 보내는 방법 (0) | 2023.02.11 |