Search code examples
javascriptangularjsangularsingle-page-applicationsystemjs

How to handle version of files in angular 2


In current angular app 1.x, I use a custom module and file loader, which allow me adding a suffix(v=x.y) to file url. Browser will base on that suffix to load file from cache or take it from server. Such as:

'app/user/user.services.js?v=1.2',
'app/order/order.services.js?v=1.3',

Version numbers(1.2, 1.3...) is set dynamically in each user session by my loader, version number for each file can be different.

On angular 2, with SystemJs, how can I define version number for files imported by SystemJs used in my app.

Suggesting me some other loaders to solve this case is highly appreciated!


Solution

  • After working a round, I found a solution for this. Before running system.config.js, I will load a version number from server by a request. And we have a version number for app at start time.

    var vQuery = '?v=1.3';
    

    Then I can added a prefix to every request by config package in systemjs. It is just by adding a prefix to value of defaultExtension

    packages: {
      app: {
          main: './main',
          defaultExtension: 'ts' + vQuery
      }
    }
    

    After that, when SystemJS load a file, it will automatically add a prefix(?v=1.3) to file url such as:

    /src/components/todoList.ts?v=1.3
    /src/components/newTodo.ts?v=1.3
    

    We can also add a different version number for each package by generating a config for each package and add it dynamically to SystemJS. Config code as below:

    var ngPackageNames = ['all','of your','packages'];
    
    // list of configs for each package
    var packages = [];
    
    //method to find version for each package
    getVersionOfFile: function(package){
        // find version of package and return
        return 'v=' + 'version of this package';
    }
    
    // generate config
    ngPackageNames.forEach(function(package){
       // handle config for this package
       packages[pkgName] = { main: packageFile, defaultExtension: 'ts' +  getVersionOfFile(package) };
    });
    
    // at last, add config for all packages to SystemJS
    var config = {
        map: map,
        packages: packages
    }
    
    System.config(config);