HTML bundling in Angular2

2019-09-13 19:30发布

问题:

I've already managed to bundle all of my JS files with SystemJS Builder. Now, I want to minify and concat all of my html files.

However, in my components, I use:

tempalateUrl: '....'

Now:

  1. How can I bundle html's into one file?
  2. Will angular2 see those htmls out of the box?

回答1:

There's a gulp plugin that does the job nicely gulp-inline-ng2-template. This is the task I'm using (a bit long, because of the CSS processing pipeline):

gulp
  .src('src/app/**/*.ts', { since: gulp.lastRun('typescript') })
  .pipe(plugins.replace('.css', '.styl'))
  .pipe(plugins.inlineNg2Template({
    useRelativePaths: true,
    removeLineBreaks: true,
    supportNonExistentFiles: true,
    templateProcessor: (ext, content, cb) => {
      try {
        const minify = require('html-minifier').minify;
        var html = minify(content, {
          collapseWhitespace: true,
          caseSensitive: true,
          removeComments: true,
          removeRedundantAttributes: true
        });
        cb(null, html);
      } catch (err) { cb(err); }
    },
    styleProcessor: (ext, content, cb) => {
      try {
        const postcss = require('postcss');
        const csso = require('csso');
        const autoprefixer = require('autoprefixer');
        const stylus = require('stylus');

        var css = stylus.render(content);
        css = postcss([autoprefixer]).process(css).css;
        css = csso.minify(css).css;
        cb(null, css);
      } catch (err) { cb(err); }
    },
  }))
  .pipe(plugins.typescript(tsProject, undefined, tsReporter))
  .pipe(gulp.dest('dist'));

Once you compile files like this, you can use them normally with systemjs bundler... Also, this is for gulp 4, if some options are strange, that's why (:



标签: angular gulp