filipesilva / angular-quickstart-lib

MIT License
305 stars 75 forks source link

Angular Source included in UMD Bundle #40

Open CarstenLeue opened 7 years ago

CarstenLeue commented 7 years ago

I'd like to use your seed to write an Angular lib that in turn depends on another angular lib. In my case this compiles, but the Angular sources are included in the UMD bundle of my lib. How I can prevent this from happening?

My build config is this:

'use strict';

const fs = require('fs');
const path = require('path');
const glob = require('glob');
const camelCase = require('camelcase');
const ngc = require('@angular/compiler-cli/src/main').main;
const rollup = require('rollup');
const uglify = require('rollup-plugin-uglify');
const sourcemaps = require('rollup-plugin-sourcemaps');
const nodeResolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');

const inlineResources = require('./inline-resources');

const libName = require('./package.json').name;
const rootFolder = path.join(__dirname);
const compilationFolder = path.join(rootFolder, 'out-tsc');
const srcFolder = path.join(rootFolder, 'src/lib');
const distFolder = path.join(rootFolder, 'dist');
const tempLibFolder = path.join(compilationFolder, 'lib');
const es5OutputFolder = path.join(compilationFolder, 'lib-es5');
const es2015OutputFolder = path.join(compilationFolder, 'lib-es2015');

return Promise.resolve()
  // Copy library to temporary folder and inline html/css.
  .then(() => _relativeCopy(`**/*`, srcFolder, tempLibFolder)
    .then(() => inlineResources(tempLibFolder))
    .then(() => console.log('Inlining succeeded.'))
  )
  // Compile to ES2015.
  .then(() => ngc({ project: `${tempLibFolder}/tsconfig.lib.json` })
    .then(exitCode => exitCode === 0 ? Promise.resolve() : Promise.reject())
    .then(() => console.log('ES2015 compilation succeeded.'))
  )
  // Compile to ES5.
  .then(() => ngc({ project: `${tempLibFolder}/tsconfig.es5.json` })
    .then(exitCode => exitCode === 0 ? Promise.resolve() : Promise.reject())
    .then(() => console.log('ES5 compilation succeeded.'))
  )
  // Copy typings and metadata to `dist/` folder.
  .then(() => Promise.resolve()
    .then(() => _relativeCopy('**/*.d.ts', es2015OutputFolder, distFolder))
    .then(() => _relativeCopy('**/*.metadata.json', es2015OutputFolder, distFolder))
    .then(() => console.log('Typings and metadata copy succeeded.'))
  )
  // Bundle lib.
  .then(() => {
    // Base configuration.
    const es5Entry = path.join(es5OutputFolder, `${libName}.js`);
    const es2015Entry = path.join(es2015OutputFolder, `${libName}.js`);
    const rollupBaseConfig = {
      moduleName: camelCase(libName),
      sourceMap: true,
      // ATTENTION:
      // Add any dependency or peer dependency your library to `globals` and `external`.
      // This is required for UMD bundle users.
      globals: {
        // The key here is library name, and the value is the the name of the global variable name
        // the window object.
        // See https://github.com/rollup/rollup/wiki/JavaScript-API#globals for more.
        '@angular/core': 'ng.core',
        'prod-wch-sdk-ng4': 'prodWchSdkNg4',
        'rxjs/Subject': 'Rx.Subject'
      },
      external: [
        // List of dependencies
        // See https://github.com/rollup/rollup/wiki/JavaScript-API#external for more.
        '@angular/core',
        '@angular/http',
        '@angular/router',
        '@ng-bootstrap/ng-bootstrap',
        'prod-wch-sdk-ng4',
        'handlebars/dist/handlebars',
        'jquery/dist/jquery.slim',
        'rxjs',
        'rxjs/add/operator/takeUntil',
        'rxjs/add/operator/catch',
        'rxjs/add/operator/delay',
        'rxjs/add/operator/first',
        'rxjs/add/observable/of',
        'rxjs/add/operator/publishReplay',
        'rxjs/add/operator/mergeMap',
        'rxjs/add/operator/startWith',
        'rxjs/add/observable/concat',
        'rxjs/add/observable/merge',
        'rxjs/add/operator/switchMap',
        'rxjs/add/operator/share',
        'rxjs/add/operator/timeInterval',
        'rxjs/add/operator/merge',
        'rxjs/add/operator/retry',
        'rxjs/add/operator/retryWhen',
        'rxjs/add/operator/delayWhen',
        'rxjs/add/operator/multicast',
        'rxjs/add/operator/distinct',
        'rxjs/add/operator/distinctUntilChanged',
        'rxjs/add/operator/filter',
        'rxjs/add/operator/shareReplay',
        'rxjs/add/observable/interval',
        'rxjs/add/observable/empty',
        'rxjs/add/observable/combineLatest',
        'rxjs/add/observable/from',
        'rxjs/Observable',
        'rxjs/Subject',
        'rxjs/ReplaySubject',
        'rxjs/BehaviorSubject',
        'rxjs/add/operator/do',
        'rxjs/add/operator/map',
        'rxjs/add/observable/timer'
      ],
      plugins: [
        commonjs({
          //include: ['node_modules/rxjs/**']
        }),
        sourcemaps(),
        nodeResolve({ jsnext: true, module: true })
      ]
    };

    // UMD bundle.
    const umdConfig = Object.assign({}, rollupBaseConfig, {
      entry: es5Entry,
      dest: path.join(distFolder, `bundles`, `${libName}.umd.js`),
      format: 'umd',
    });

    // Minified UMD bundle.
    const minifiedUmdConfig = Object.assign({}, rollupBaseConfig, {
      entry: es5Entry,
      dest: path.join(distFolder, `bundles`, `${libName}.umd.min.js`),
      format: 'umd',
      plugins: rollupBaseConfig.plugins.concat([uglify({})])
    });

    // ESM+ES5 flat module bundle.
    const fesm5config = Object.assign({}, rollupBaseConfig, {
      entry: es5Entry,
      dest: path.join(distFolder, `${libName}.es5.js`),
      format: 'es'
    });

    // ESM+ES2015 flat module bundle.
    const fesm2015config = Object.assign({}, rollupBaseConfig, {
      entry: es2015Entry,
      dest: path.join(distFolder, `${libName}.js`),
      format: 'es'
    });

    const allBundles = [
      umdConfig,
      minifiedUmdConfig,
      fesm5config,
      fesm2015config
    ].map(cfg => rollup.rollup(cfg).then(bundle => bundle.write(cfg)));

    return Promise.all(allBundles)
      .then(() => console.log('All bundles generated successfully.'))
  })
  // Copy package files
  .then(() => Promise.resolve()
    .then(() => _relativeCopy('LICENSE', rootFolder, distFolder))
    .then(() => _relativeCopy('package.json', rootFolder, distFolder))
    .then(() => _relativeCopy('README.md', rootFolder, distFolder))
    .then(() => console.log('Package files copy succeeded.'))
  )
  .catch(e => {
    console.error('\Build failed. See below for errors.\n');
    console.error(e);
    process.exit(1);
  });

// Copy files maintaining relative paths.
function _relativeCopy(fileGlob, from, to) {
  return new Promise((resolve, reject) => {
    glob(fileGlob, { cwd: from, nodir: true }, (err, files) => {
      if (err) reject(err);
      files.forEach(file => {
        const origin = path.join(from, file);
        const dest = path.join(to, file);
        const data = fs.readFileSync(origin, 'utf-8');
        _recursiveMkDir(path.dirname(dest));
        fs.writeFileSync(dest, data);
        resolve();
      })
    })
  });
}

// Recursively create a dir.
function _recursiveMkDir(dir) {
  if (!fs.existsSync(dir)) {
    _recursiveMkDir(path.dirname(dir));
    fs.mkdirSync(dir);
  }
}
desfero commented 7 years ago

For UMD bundle you need to mention all external libraries in globals (rollupBaseConfig). Because UMD bundle need where in globals it can find this library.

CarstenLeue commented 7 years ago

Thanks, that already helps a step further. Looks like this has to include the transitive dependencies, too. The new code is:

      globals: {
        // The key here is library name, and the value is the the name of the global variable name
        // the window object.
        // See https://github.com/rollup/rollup/wiki/JavaScript-API#globals for more.
        '@angular/core': 'ng.core',
        '@angular/router': 'ng.router',
        '@angular/http': 'ng.http',
        '@angular/common': 'ng.common',
        '@angular/forms': 'ng.forms',
        '@angular/platform-browser': 'ng.platformBrowser',
        '@ng-bootstrap/ng-bootstrap': 'bootstrap',
        'prod-wch-sdk-ng4': 'prodWchSdkNg4',
        'jquery/dist/jquery.slim': '$',
        'handlebars/dist/handlebars': 'Handlebars',
        'rxjs/ReplaySubject': 'Rx.ReplaySubject',
        'rxjs/BehaviorSubject': 'Rx.BehaviorSubject',
        'rxjs/Subject': 'Rx.Subject',
        'rxjs/Observable': 'Rx.Observable'
      },

This still includes the complete @ng-bootstrap/ng-bootstrap library, which is probably because I don't know what the correct global is for this library. How can I find out about this?

h657070128 commented 7 years ago

Normally I find the global name from library's UMD bundle. However, I download ng-bootstrap from npm and fails to find its global name in UMD bundle.

oscarpr commented 7 years ago

Men, can you tell me how do you do to get jquery works? I mean, what or how do you import it on your component?

tinesoft commented 6 years ago

Hi @CarstenLeue ,

have you found a solution to get ng-bootstrap NOT included in your final umd bundle?

CarstenLeue commented 6 years ago

@tinesoft I have succeeded in building a bundle without boostrap, but using a different approach than the quickstart lib. I am now using https://www.npmjs.com/package/ng-packagr to create the bundle, specifying ng-bootstrap as an external library.

The problem of not knowing the correct UMD global persists, however.

CarstenLeue commented 6 years ago

https://github.com/ng-bootstrap/ng-bootstrap/issues/2107