developer tip

Angular 2 + Typescript + systemjs 앱을 실제로 어떻게 배포합니까?

copycodes 2020. 8. 15. 09:27
반응형

Angular 2 + Typescript + systemjs 앱을 실제로 어떻게 배포합니까?


typescript 및 systemjs를 사용하는 angular.io에 빠른 시작 자습서가 있습니다. 이제 미니 앱을 실행 했으니 배포 가능한 것을 만들려면 어떻게해야할까요? 나는 그것에 대한 정보를 전혀 찾을 수 없었습니다.

System.config에 추가 도구, 추가 설정이 필요합니까?

(나는 webpack을 사용하고 하나의 bundle.js를 만들 수 있다는 것을 알고 있지만 튜토리얼에서 사용되는 systemjs를 사용하고 싶습니다)

누군가가이 설정 (Angular 2, TypeScript, systemjs)과 빌드 프로세스를 공유 할 수 있습니까?


이 수준에서 이해해야 할 핵심 사항은 다음 구성을 사용하면 컴파일 된 JS 파일을 직접 연결할 수 없다는 것입니다.

TypeScript 컴파일러 구성에서 :

{
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "declaration": false,
    "stripInternal": true,
    "module": "system",
    "moduleResolution": "node",
    "noEmitOnError": false,
    "rootDir": ".",
    "inlineSourceMap": true,
    "inlineSources": true,
    "target": "es5"
  },
  "exclude": [
    "node_modules"
  ]
}

HTML에서

System.config({
  packages: {
    app: {
      defaultExtension: 'js',
      format: 'register'
    }
  }
});

실제로 이러한 JS 파일에는 익명 모듈이 포함됩니다. 익명 모듈은 System.register모듈 이름을 첫 번째 매개 변수로 사용 하지만 사용 하지 않는 JS 파일입니다 . 이것은 typescript 컴파일러가 systemjs가 모듈 관리자로 구성 될 때 기본적으로 생성하는 것입니다.

따라서 모든 모듈을 단일 JS 파일로 만들 outFile려면 TypeScript 컴파일러 구성 내 에서 속성 을 활용해야 합니다.

이를 위해 gulp 내부에서 다음을 사용할 수 있습니다.

const gulp = require('gulp');
const ts = require('gulp-typescript');

var tsProject = ts.createProject('tsconfig.json', {
  typescript: require('typescript'),
  outFile: 'app.js'
});

gulp.task('tscompile', function () {
  var tsResult = gulp.src('./app/**/*.ts')
                     .pipe(ts(tsProject));

  return tsResult.js.pipe(gulp.dest('./dist'));
});

이것은 다른 처리와 결합 될 수 있습니다.

  • 컴파일 된 TypeScript 파일을 uglify하려면
  • app.js파일 을 만들려면
  • vendor.js타사 라이브러리 용 파일 을 만들려면
  • boot.js응용 프로그램을 부트 스트랩하는 모듈을 가져올 파일 을 만듭니다 . 이 파일은 페이지 끝에 포함되어야합니다 (모든 페이지가로드 될 때).
  • index.html이 두 파일을 고려 하여 업데이트하려면

gulp 작업에는 다음 종속성이 사용됩니다.

  • 꿀꺽 꿀꺽
  • gulp-html-replace
  • 꿀꺽 꿀꺽 타이프 스크립트
  • 꿀꺽 꿀꺽 마시다

다음은 적용 할 수있는 샘플입니다.

  • app.min.js파일 생성

    gulp.task('app-bundle', function () {
      var tsProject = ts.createProject('tsconfig.json', {
        typescript: require('typescript'),
        outFile: 'app.js'
      });
    
      var tsResult = gulp.src('app/**/*.ts')
                       .pipe(ts(tsProject));
    
      return tsResult.js.pipe(concat('app.min.js'))
                    .pipe(uglify())
                    .pipe(gulp.dest('./dist'));
    });
    
  • vendors.min.js파일 생성

    gulp.task('vendor-bundle', function() {
      gulp.src([
        'node_modules/es6-shim/es6-shim.min.js',
        'node_modules/systemjs/dist/system-polyfills.js',
        'node_modules/angular2/bundles/angular2-polyfills.js',
        'node_modules/systemjs/dist/system.src.js',
        'node_modules/rxjs/bundles/Rx.js',
        'node_modules/angular2/bundles/angular2.dev.js',
        'node_modules/angular2/bundles/http.dev.js'
      ])
      .pipe(concat('vendors.min.js'))
      .pipe(uglify())
      .pipe(gulp.dest('./dist'));
    });
    
  • boot.min.js파일 생성

    gulp.task('boot-bundle', function() {
      gulp.src('config.prod.js')
        .pipe(concat('boot.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('./dist'));
     });
    

    config.prod.js단순히 다음을 포함합니다

     System.import('boot')
        .then(null, console.error.bind(console));
    
  • index.html파일 업데이트

    gulp.task('html', function() {
      gulp.src('index.html')
        .pipe(htmlreplace({
          'vendor': 'vendors.min.js',
          'app': 'app.min.js',
          'boot': 'boot.min.js'
        }))
        .pipe(gulp.dest('dist'));
    });
    

    index.html다음과 같다 :

    <html>
      <head>
        <!-- Some CSS -->
    
        <!-- build:vendor -->
        <script src="node_modules/es6-shim/es6-shim.min.js"></script>
        <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
        <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
        <script src="node_modules/systemjs/dist/system.src.js"></script>
        <script src="node_modules/rxjs/bundles/Rx.js"></script>
        <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
        <script src="node_modules/angular2/bundles/http.dev.js"></script>
        <!-- endbuild -->
    
        <!-- build:app -->
        <script src="config.js"></script>
        <!-- endbuild -->
      </head>
    
      <body>
        <my-app>Loading...</my-app>
    
        <!-- build:boot -->
        <!-- endbuild -->
      </body>
    </html>
    

이 있음을주의 System.import('boot');모든 앱 구성 요소가에서 등록 할 때까지 기다릴 몸의 끝에서해야 app.min.js파일.

여기서는 CSS 및 HTML 축소를 처리하는 방법을 설명하지 않습니다.


angular2-cli 빌드 명령을 사용할 수 있습니다.

ng build -prod

https://github.com/angular/angular-cli/wiki/build#bundling

로 만든 빌드 -prod를 통해 플래그 ng build -prod또는 ng serve -prod에 모든 종속성을 번들 하나의 파일 , 그리고 사용하게 나무 흔드는 기술을.

최신 정보

이 답변은 angular2가 rc4에있을 때 제출되었습니다.

angular-cli beta21 및 angular2 ^ 2.1.0에서 다시 시도했으며 예상대로 작동합니다.

이 답변은 사용할 수있는 angular-cli로 앱을 초기화해야합니다.

ng new myApp

또는 기존에

ng init

업데이트 2018/08/06

각도 6의 경우 구문이 다릅니다.

ng build --prod --build-optimizer

문서 확인


GulpSystemJS-Builder함께 SystemJS를 사용하여 Typescript에서 Angular 2 (2.0.0-rc.1) 프로젝트를 빌드 할 수 있습니다 .

아래는 2.0.0-rc.1을 실행하는 Tour of Heroes를 빌드, 번들링 및 축소하는 방법의 단순화 된 버전입니다 ( 전체 소스 , 라이브 예제 ).

gulpfile.js

var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var typescript = require('gulp-typescript');
var systemjsBuilder = require('systemjs-builder');

// Compile TypeScript app to JS
gulp.task('compile:ts', function () {
  return gulp
    .src([
        "src/**/*.ts",
        "typings/*.d.ts"
    ])
    .pipe(sourcemaps.init())
    .pipe(typescript({
        "module": "system",
        "moduleResolution": "node",
        "outDir": "app",
        "target": "ES5"
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('app'));
});

// Generate systemjs-based bundle (app/app.js)
gulp.task('bundle:app', function() {
  var builder = new systemjsBuilder('public', './system.config.js');
  return builder.buildStatic('app', 'app/app.js');
});

// Copy and bundle dependencies into one file (vendor/vendors.js)
// system.config.js can also bundled for convenience
gulp.task('bundle:vendor', function () {
    return gulp.src([
        'node_modules/jquery/dist/jquery.min.js',
        'node_modules/bootstrap/dist/js/bootstrap.min.js',
        'node_modules/es6-shim/es6-shim.min.js',
        'node_modules/es6-promise/dist/es6-promise.min.js',
        'node_modules/zone.js/dist/zone.js',
        'node_modules/reflect-metadata/Reflect.js',
        'node_modules/systemjs/dist/system-polyfills.js',
        'node_modules/systemjs/dist/system.src.js',
      ])
        .pipe(concat('vendors.js'))
        .pipe(gulp.dest('vendor'));
});

// Copy dependencies loaded through SystemJS into dir from node_modules
gulp.task('copy:vendor', function () {
  gulp.src(['node_modules/rxjs/**/*'])
    .pipe(gulp.dest('public/lib/js/rxjs'));

  gulp.src(['node_modules/angular2-in-memory-web-api/**/*'])
    .pipe(gulp.dest('public/lib/js/angular2-in-memory-web-api'));
  
  return gulp.src(['node_modules/@angular/**/*'])
    .pipe(gulp.dest('public/lib/js/@angular'));
});

gulp.task('vendor', ['bundle:vendor', 'copy:vendor']);
gulp.task('app', ['compile:ts', 'bundle:app']);

// Bundle dependencies and app into one file (app.bundle.js)
gulp.task('bundle', ['vendor', 'app'], function () {
    return gulp.src([
        'app/app.js',
        'vendor/vendors.js'
        ])
    .pipe(concat('app.bundle.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./app'));
});

gulp.task('default', ['bundle']);

system.config.js

var map = {
  'app':                                'app',
  'rxjs':                               'vendor/rxjs',
  'zonejs':                             'vendor/zone.js',
  'reflect-metadata':                   'vendor/reflect-metadata',
  '@angular':                           'vendor/@angular'
};

var packages = {
  'app':                                { main: 'main', defaultExtension: 'js' },
  'rxjs':                               { defaultExtension: 'js' },
  'zonejs':                             { main: 'zone', defaultExtension: 'js' },
  'reflect-metadata':                   { main: 'Reflect', defaultExtension: 'js' }
};

var packageNames = [
  '@angular/common',
  '@angular/compiler',
  '@angular/core',
  '@angular/http',
  '@angular/platform-browser',
  '@angular/platform-browser-dynamic',
  '@angular/router',
  '@angular/router-deprecated',
  '@angular/testing',
  '@angular/upgrade',
];

packageNames.forEach(function(pkgName) {
  packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});

System.config({
  map: map,
  packages: packages
});


Angular 2 용 MEA2N 상용구는 다음과 같습니다. https://github.com/simonxca/mean2-boilerplate

tsc사물을 하나로 묶는 데 사용하는 간단한 상용구입니다 . (실제로 핵심은 명령 인 grunt-ts를 사용합니다 tsc.) Wekpack 등이 필요하지 않습니다.

grunt 사용 여부에 관계없이 아이디어는 다음과 같습니다.

  • 라는 폴더에 응용 프로그램을 쓰기 ts/(예 : public/ts/)
  • 사용 tsc당신의 디렉토리 구조 미러링 ts/에 폴더를 js/의 폴더와 단지 참조 파일을 js/사용자의 폴더 index.html.

To get grunt-ts to work (there should be an equivalent command for plain tsc, Gulp, etc.) , you have a property in your tsconfig.json called "outDir": "../js", and reference it in your gruntfile.js with:

grunt.initConfig({
  ts: {
    source: {tsconfig: 'app/ts/tsconfig.json'}
  },
  ...
});

Then run grunt ts, which will take your app in public/ts/ and mirror it to public/js/.

There. Super easy to understand. Not the best approach, but a good one to get started.


The easiest way that I have found to bundle angular rc1 for systemJs is to use gulp and systemjs-builder:

gulp.task('bundle', function () {
    var path = require('path');
    var Builder = require('systemjs-builder');

    var builder = new Builder('/node_modules');

    return builder.bundle([
        '@angular/**/*.js'
        ], 
        'wwwroot/bundle.js', 
        { minify: false, sourceMaps: false })
        .then(function () {
            console.log('Build complete');
        })
        .catch(function (err) {
            console.log('Build error');
            console.log(err);
        });
});

As pointed out in the comments, systemJs currently has issues when bundling components using moduleId: module.id

https://github.com/angular/angular/issues/6131

The current recommendation (angular 2 rc1) seems to be to use explicit paths i.e. moduleId: '/app/path/'


I used expressjs on the backend to serve my ng2 project. You can check it from my github page: https://github.com/echonax/ng2-beta-and-test-framework


Under Angular.io website, under Advanced/Deployment section, it is recommended that the simplest way to deploy is 'to copy the development environment to the server'.

  1. go through the section under: Simplest deployment possible. The final project files are shown inside the code section. Note that it already sets up the code to load npm package files from the web (in stead of from the local npm_modules folder).

  2. make sure it is running on your local computer (npm start). Then under the project folder, copy everything under '/src' sub-folder to the S3 bucket you've set up. You can use drag-and-drop to copy, during that process, you get the option to select the permission setting for the files, make sure to make them 'readable' to 'everyone'.

  3. under bucket 'Properties' tab, look for 'Static website hosting' panel, check on 'Use this bucket to host website' option, and specify 'index.html' to both Index document and Error document.

  4. click on the static website Endpoint, your project well be running!

참고URL : https://stackoverflow.com/questions/36285064/how-do-i-actually-deploy-an-angular-2-typescript-systemjs-app

반응형