How to import a barrel by folder name only?

后端 未结 3 1178

Angular 2 Barrels

In Angular 2, I\'m trying to get barrels to work as described in the documentation.

The official Angular 2 style guide t

3条回答
  •  無奈伤痛
    2020-12-05 05:18

    AFAIK SystemJS doesn't understand barrels by itself but Webpack does. BTW, After digging up how Angular does it for it's modules, I've found a solution


    In system.config.js you'll need to do the following things

    Note: the parent directory of a index.ts is the barrel, ICYDK

    • Add the paths of your barrels

    // map tells the System loader where to look for things
      var map = {
        'app':                        'app', // 'dist',
        'rxjs':                       'node_modules/rxjs',
        'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
        '@angular':                   'node_modules/@angular',
    
        'barrel':                 'path/to/your/barrel'
      };
    
    • Don't add barrels to packages (explained later)##

    // packages tells the System loader how to load when no filename and/or no extension
      var packages = {
        'app':                        { main: 'app/boot.js',  defaultExtension: 'js' },
        'rxjs':                       { defaultExtension: 'js' },
        'angular2-in-memory-web-api': { defaultExtension: 'js' }
      };
    
    • Add them to packageNames, just like angular

    var packageNames = [
        '@angular/common',
        ...
        '@angular/upgrade',
    
        'barrel'
      ];
    

    And you're done.


    ##

    Why we used packageNames instead of packages is because you'll have to repeat the { main: 'index.js', defaultExtension: 'js' } (filename and extension) for every barrel, but angular is already doing it by looping with this.

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

    Which is ultimately adding them to packages.


    Usage

    import {something} from '../../barrel'; // relative path to directory of barrel
    

    and

    import {something} from 'barrel'; // name of barrel
    

    Both work, but the later one fails to provide intellisense and shows an error saying cannot find module 'barrel'. Which I don't have a solution for. But I'll add it when I do.

提交回复
热议问题