繁体   English   中英

如何组合(缩小)编译的Angular 2组件?

[英]How to combine (minify) compiled Angular 2 components?

试图缩小项目的编译源代码以进行生产,我正在使用Gulp作为任务运行者。

源文件看起来像这样,

HTML

<!--... . .  various scripts and styles . . . . . --->
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="node_modules/angular2/bundles/router.dev.js"></script>
<script src="node_modules/angular2/bundles/http.dev.js"></script>

<script>
  System.config({
    packages: {        
      app: {
        format: 'register',
        defaultExtension: 'js'
      }
    }
  });
  System.import('app/main')
        .then(null, console.error.bind(console));
</script>
</head>
<body>
  <app></app>
</body>

我的app目录结构如下,

.
├── main.js
├── main.js.map
├── main.ts
├── main.app.js
├── main.app.js.map
├── main.app.ts
├── x.component1
│   ├── x.component.one.js
│   ├── x.component.one.js.map
│   └── x.component.one.ts
└── x.component2
    ├── x.component.two.js
    ├── x.component.two.js.map
    └── x.component.two.ts

应用程序/ main.ts

import {bootstrap}    from 'angular2/platform/browser';
import {MyAwesomeApp} from './main.app'

bootstrap(MyAwesomeApp);

main.app.ts

@Component({
    selector: 'app',
    template: `
        <component-1></component-1>

        <component-2></component-2>
    `,
    directives: [Component1, Component2]
})


export class MyAwesomeApp {

}

那么组件,

@Component({
    selector: 'component-1',
    template: `
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae ducimus, saepe fugit illum fuga praesentium rem, similique deserunt tenetur laudantium et labore cupiditate veniam qui impedit, earum commodi quasi sequi.
    `
})


export class Component1 {

}

@Component({
    selector: 'component-2',
    template: `
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae ducimus, saepe fugit illum fuga praesentium rem, similique deserunt tenetur laudantium et labore cupiditate veniam qui impedit, earum commodi quasi sequi.
    `
})


export class Component2 {

}

所有TypeScript文件都编译为ES5 JavaScript,还需要缩小为main.js

所以我的问题是,

  1. 我是否可以运行任务来收集所有已编译的.js文件以缩小为单个文件并将其作为生产分支中的main文件引用?
  2. 这是否会从'y'中断模块系统import {x}?
  3. 如果它打破了模块加载系统,可以做什么来连接Angular 2应用程序上的文件?

我的TypeScript版本是1.8.2

感谢您的任何帮助。

如果要将所有TypeScript文件编译为单个文件,则需要使用TypeScript编译器的outFile属性。 它可以通过gulp-typescript插件进行配置。

这样您就不需要配置SystemJS来根据文件名加载模块:

<script>
  // Not necessary anymore
  /* System.config({
    packages: {        
      app: {
        format: 'register',
        defaultExtension: 'js'
      }
    }
  }); */
  System.import('app/main')
        .then(null, console.error.bind(console));
</script>

模块名称及其内容现在存在于此单个文件中。 Angular2发行版的打包捆绑文件的方式相同( angular2.dev.jshttp.dev.js ,...)。 要使用此文件,只需将其包含在script元素中即可。

这样您就不会破坏模块导入。

然后你可以使用gulp的uglify插件缩小这个单个文件...

**使用tsconfig.json中的选项从TS创建单个文件。

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": true,
    "noImplicitAny": false,
    "outDir":"client/build/",
    "outFile": "client/build/all.js",
    "declaration": true
  },
  "exclude": [
    "node_modules",
    "server"
  ],
  "include": [
        "client/*.ts",
        "client/**/*.ts",
        "client/**/**/*.ts"
  ]   
}

// Include all folders to put to a file.

**构建输出文件并包括如下:示例:

<script>


  // Alternative way is compile in all.js and use the following system config with all the modules added to the bundles.
  // the bundle at build/all.js contains these modules
System.config({
    bundles: {
      'client/build/all.js': ['boot','components/all/present','components/main/main','components/register/register','components/login/login','components/home/home','services/userdetails','services/httpprovider']
    }
  });

  // when we load 'app/app' the bundle extension interrupts the loading process
  // and ensures that boot of build/all.js is loaded first
  System.import('boot');


    </script>

**正常情况下缩小all.js文件。

由于您已经在使用Gulp,因此您可以在gulp任务中添加webpack ,将所有JavaScript源文件(以及Angular2源)合并为一个。 以下是webpack.config.js的示例:

module.exports = {
  entry: './src/app/app',
  output: {
    path: __dirname + '/src', publicPath: 'src/', filename: 'bundle.js'
  },
  resolve: {
    extensions: ['', '.js', '.ts']
  },
  module: {
    loaders: [{
      test: /\.ts/, loaders: ['ts-loader'], exclude: /node_modules/
    }]
  }
};

你的gulpfile.js的相关部分是

var webpack = require('webpack-stream');
var htmlReplace = require('gulp-html-replace');
var gulp = require('gulp');

gulp.task('webpack', function() {
  return gulp.src('src/app/*.ts')
    .pipe(webpack(require('./webpack.config.js')))
    .pipe(gulp.dest('src/'));
});

gulp.dest('src/')替换为您希望生产代码驻留的相关位置。

然后,您需要处理HTML文件以获得适当的JavaScript源文件引用(也在gulpfile.js中 )。

gulp.task('html', ['templates'], function() {
  return gulp.src('src/index.html')
    .pipe(htmlReplace({
      'js': ['bundle.js']
    }))
    .pipe(gulp.dest('dist/'));
});

如果您想缩小JavaScript文件,可以使用UglifyJS2 (但请注意,混淆会出现问题,因此错误mangle: false 。请参阅此SO链接了解更多信息)。 这是相关的gulpfile.js内容:

gulp.task('js', ['webpack'], function() {
  return gulp.src('src/bundle.js')
    .pipe(uglify({
            mangle: false
          }))
    .pipe(gulp.dest('dist/'));
});

通过这种方式,您的生产代码最终会在您可以部署它的dist文件夹中。 现在您可以选择是否将其检入生产分支。

如果你想在一个非常小的Angular2应用程序上看到一个工作版本,请随意参考我在Github上的单词项目

如果您使用的是@angular/cli ,则可以运行

ng build --prod

缩小和压缩代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM