IT

Angular 앱을 어떻게 배포합니까?

lottoking 2020. 5. 20. 08:13
반응형

Angular 앱을 어떻게 배포합니까?


Angular 앱이 프로덕션 단계에 도달하면 어떻게 배포합니까?

지금까지 본 모든 가이드 ( angular.io조차도 )는 변경 사항을 반영하기 위해 lite-server를 제공하고 browserSync에 의존하고 있지만 개발이 끝나면 앱을 게시하는 방법은 무엇입니까?

페이지 에서 컴파일 된 .js파일을 모두 가져 index.html오거나 gulp를 사용하여 축소합니까? 그들은 작동합니까? 프로덕션 버전에서 SystemJS가 필요합니까?


실제로 하나의 질문에 두 가지 질문이 있습니다. 첫 번째는 응용 프로그램을 호스팅하는 방법입니다. 그리고 @toskv는 대답하기에는 너무 광범위한 질문을 언급했으며 수많은 다른 것들에 달려 있습니다. 두 번째는 더 구체적입니다. 응용 프로그램의 배포 버전을 어떻게 준비합니까? 여기 몇 가지 옵션이 있습니다.

  1. 그대로 배포하십시오. 그냥-축소, 연결, 이름 맹 글링 등이 없습니다. 모든 ts 프로젝트를 번역하고 모든 결과 js / css / ... 소스 + 종속성을 호스팅 서버에 복사하십시오.
  2. 특수 번들링 도구를 사용하여 배포하십시오. webpack 또는 systemjs 빌더와 같습니다. 그들은 # 1에서 부족한 모든 가능성을 가지고 있습니다. 모든 앱 코드를 html에서 참조하는 몇 가지 js / css / ... 파일로 압축 할 수 있습니다. Systemjs buider를 사용하면 배포 패키지의 일부로 systemjs를 포함시킬 필요가 없습니다.

예, 패키지의 일부로 systemjs와 다른 많은 외부 라이브러리를 배포해야 할 것입니다. 그리고 네, html 페이지에서 참조하는 몇 개의 js 파일로 묶을 수 있습니다. 페이지에서 컴파일 된 모든 js 파일을 참조 할 필요는 없습니다. 모듈 로더 인 systemjs가 처리합니다.

나는 그것이 진흙탕처럼 들린다는 것을 알고 있습니다-여기 # 2를 시작하는 데 도움이되는 두 가지 샘플 응용 프로그램이 있습니다.

SystemJS 빌더 : angular2 seed

WebPack : angular2 웹팩 스타터

그들이 어떻게하는지보십시오-그리고 이것이 당신이 만드는 응용 프로그램을 묶는 방법을 찾는 데 도움이되기를 바랍니다.


간단한 대답. Angular CLI를 사용하여

ng build 

프로젝트의 루트 디렉토리에있는 명령. 사이트는 dist 디렉토리에 작성되며 모든 웹 서버에 배치 할 수 있습니다.

앱에 프로덕션 설정이있는 경우 테스트를 위해 빌드해야합니다.

ng build --prod

그러면 dist디렉토리에 프로젝트가 빌드 되고 서버로 푸시 될 수 있습니다.

이 답변을 처음 게시 한 이후 많은 일이 발생했습니다. CLI는 최종적으로 1.0.0에 있으므로이 가이드를 따라 프로젝트를 빌드하기 전에 업그레이드해야합니다. https://github.com/angular/angular-cli/wiki/stories-rc-update


Angular CLI를 사용하면 쉽습니다. 헤 로쿠의 예 :

  1. Heroku 계정을 생성하고 CLI를 설치하십시오

  2. 이동 angular-cli받는 출발을 dependencies에서 package.json당신에게 Heroku를 누르면이 설치됩니다 그래서 (.

  3. 코드가 Heroku로 푸시 될 때 postinstall실행될 스크립트를 추가하십시오 ng build. 또한 다음 단계에서 작성 될 노드 서버에 대한 시작 명령을 추가하십시오. 그러면 앱의 정적 파일 dist이 서버 디렉토리에 배치되고 나중에 앱이 시작됩니다.

"scripts": {
  // ...
  "start": "node server.js",
  "postinstall": "ng build --aot -prod"
}
  1. 앱을 제공 할 Express 서버를 만듭니다.
// server.js
const express = require('express');
const app = express();
// Run the app by serving the static files
// in the dist directory
app.use(express.static(__dirname + '/dist'));
// Start the app by listening on the default
// Heroku port
app.listen(process.env.PORT || 8080);
  1. Heroku 리모컨을 만들고 앱을 밀어 넣으십시오.
heroku create
git add .
git commit -m "first deploy"
git push heroku master

여기에 빠른입니다 작성자 어떻게 처리하는 HTTPS 등을 사용 요청을 강제하는 방법을 포함한 자세한 내용을 가지고 내가 한이 PathLocationStrategy:)


잘하면 이것이 도움이 될 수 있기를 바랍니다. 그리고 일주일 동안 이것을 시도 할 수 있기를 바랍니다.

  1. Azure에서 웹앱 만들기
  2. 코드 대 Angular 2 앱을 만듭니다.
  3. bundle.js에 웹팩.
  4. Azure 사이트 게시 된 프로필 XML 다운로드
  5. 사이트 프로필과 함께 https://www.npmjs.com/package/azure-deploy사용하여 Azure-deploy를 구성 하십시오 .
  6. 배포합니다.
  7. 크림 맛.

나는 영원히 함께 사용합니다 :

  1. angular-cli

    to dist 폴더를 사용하여 Angular 응용 프로그램 빌드ng build --prod --output-path ./dist
  2. Angular 애플리케이션 경로에 server.js 파일을 작성하십시오 .

    const express = require('express');
    const path = require('path');
    
    const app = express();
    
    app.use(express.static(__dirname + '/dist'));
    
    app.get('/*', function(req,res) {
        res.sendFile(path.join(__dirname + '/dist/index.html'));
    });
    app.listen(80);
    
  3. 영원히 시작 forever start server.js

그게 다야! 응용 프로그램이 실행 중이어야합니다!


Angular2 앱을 프로덕션 서버에 배포하려면 가장 먼저 앱이 컴퓨터에서 로컬로 실행되도록하십시오.

Angular2 앱은 노드 앱으로 배포 할 수도 있습니다.

따라서 노드 진입 점 파일 server.js / app.js를 작성하십시오 (이 예제에서는 express 사용).

var express = require('express'),
    path = require('path'),
    fs = require('fs');

var app = express();
var staticRoot = __dirname + '/';

app.set('port', (process.env.PORT || 3000));

app.use(express.static(staticRoot));

app.use(function(req, res, next){

    // if the request is not html then move along
    var accept = req.accepts('html', 'json', 'xml');
    if(accept !== 'html'){
        return next();
    }

    // if the request has a '.' assume that it's for a file, move along
    var ext = path.extname(req.path);
    if (ext !== ''){
        return next();
    }

    fs.createReadStream(staticRoot + 'index.html').pipe(res);

}); 

app.listen(app.get('port'), function() {
    console.log('app running on port', app.get('port'));
});

또한 package.json 파일에 종속성으로 express추가 하십시오.

그런 다음 원하는 환경에 배치하십시오.

I have put together a small blog for deployment on IIS. follow link


To Deploy your application in IIS follow the below steps.

Step 1: Build your Angular application using command ng build --prod

Step 2: After build all files are stored in dist folder of your application path.

Step 3: Create a folder in C:\inetpub\wwwroot by name QRCode.

Step 4: Copy the contents of dist folder to C:\inetpub\wwwroot\QRCode folder.

Step 5: Open IIS Manager using command (Window + R) and type inetmgr click OK.

Step 6: Right click on Default Web Site and click on Add Application.

Step 7: Enter Alias name 'QRCode' and set the physical path to C:\inetpub\wwwroot\QRCode.

Step 8: Open index.html file and find the line href="\" and remove '\'.

Step 9: Now browse application in any browser.

You can also follow the video for better understanding.

Video url: https://youtu.be/F8EI-8XUNZc


If you deploy your application in Apache (Linux server) so you can follow following steps : Follow following steps :

Step 1: ng build --prod --env=prod

Step 2. (Copy dist into server) then dist folder created, copy dist folder and deploy it in root directory of server.

Step 3. Creates .htaccess file in root folder and paste this in the .htaccess

 <IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

If You test app like me on localhost or You will have some problems with blank white page i use this:

ng build --prod --build-optimizer --base-href="http://127.0.0.1/my-app/"

Explanation:

ng build

Build app but there is many spaces, tabs and other stuff. For server it isnt important how code looks. This is why i use:

ng build --prod --build-optimizer 

This make code out for production and reduce size [--build-optimizer] allow to reduce more code].

So at end i add --base-href="http://127.0.0.1/my-app/" to show application where is 'main frame' [in simple words]. With it You can have even multiple angular apps in any folder.


You get the smallest and quickest loading production bundle by compiling with the Ahead of Time compiler, and tree-shake/minify with rollup as shown in the angular AOT cookbook here: https://angular.io/docs/ts/latest/cookbook/aot-compiler.html

This is also available with the Angular-CLI as said in previous answers, but if you haven't made your app using the CLI you should follow the cookbook.

I also have a working example with materials and SVG charts (backed by Angular2) that it includes a bundle created with the AOT cookbook. You also find all the config and scripts needed to create the bundle. Check it out here: https://github.com/fintechneo/angular2-templates/

I made a quick video demonstrating the difference between number of files and size of an AoT compiled build vs a development environment. It shows the project from the github repository above. You can see it here: https://youtu.be/ZoZDCgQwnmQ


Angular 2 Deployment in Github Pages

Testing Deployment of Angular2 Webpack in ghpages

First get all the relevant files from the dist folder of your application, for me it was the : + css files in the assets folder + main.bundle.js + polyfills.bundle.js + vendor.bundle.js

Then push this files in the repo which you have created.

1 -- If you want the application to run on the root directory - create a special repo with the name [yourgithubusername].github.io and push these files in the master branch

2 -- Where as if you want to create these page in the sub directory or in a different branch other than than the root, create a branch gh-pages and push these files in that branch.

In both the cases the way we access these deployed pages will be different.

For the First case it will be https://[yourgithubusername].github.io and for the second case it will be [yourgithubusername].github.io/[Repo name].

If suppose you want to deploy it using the second case make sure to change the base url of the index.html file in the dist as all the route mappings depend on the path you give and it should be set to [/branchname].

Link to this page

https://rahulrsingh09.github.io/Deployment

Git Repo

https://github.com/rahulrsingh09/Deployment


For a quick and cheap way to host an angular app, I have been using the Firbase hosting. It's free on the first tier and very easy to deploy new versions using the Firebase CLI. This article here explains the necessary steps to deploy your production angular 2 app to Firebase: https://medium.com/codingthesmartway-com-blog/hosting-angular-2-applications-on-firebase-f194688c978d

In short, you run ng build --prod which creates a dist folder in the package and that's the folder that gets deployed to Firebase Hosting.


Deploying Angular 2 in azure is easy

  1. Run ng build --prod , which will generate a dist folder with everything bundled inside few files including index.html.

  2. Create a resource group and a web app inside it.

  3. Place your dist folders files using FTP. In azure it will look for index.html to the run the application.

That's it. Your app is running !


As of 2017 the best way is to use angular-cli (v1.4.4) for your angular project.

ng build --prod --env=prod --aot --build-optimizer --output-hashing none

You needn't add --aot explicitly as its turned on by default with --prod.And the use of --output-hashing is as per your personal preference regarding cache bursting.

You could explicitly add CDN support by adding :

 --deploy-url "https://<your-cdn-key>.cloudfront.net/"

if you plan to use CDN for hosting which is considerably fast.


With Angular CLI, you can use the following command:

ng build --prod

It generates a dist folder with all you need to deploy the application.

If you have no practice with web servers, I recommend you to use Angular to Cloud. You just need to compress the dist folder as zip file and upload it in the platform.


I would say a lot of people with Web experience prior to angular, are use to deploying their web artifacts inside a war (i.e. jquery and html inside a Java/Spring project). I ended up doing this to get around CORS issue, after attempting to keep my angular and REST projects separate.

My solution was to move all angular (4) contents, generated with CLI, from my-app to MyJavaApplication/angular. Then I modifed my Maven build to use maven-resources-plugin to move the contents from /angular/dist to the root of my distribution (i.e. $project.build.directory}/MyJavaApplication). Angular loads resources from root of the war by default.

When I started to add routing to my angular project, I further modifed maven build to copy index.html from /dist to WEB-INF/app. And, added a Java controller that redirects all server side rest calls to index.


Just follow the below link,

Change your Index.html page Script File paths Change your component.html path incase your getting error that could not find the location

https://angular.io/docs/ts/latest/guide/deployment.html#!#dev-deploy

참고URL : https://stackoverflow.com/questions/35539622/how-do-you-deploy-angular-apps

반응형