Search code examples
angulartypescriptrollupjsangular-library

Build Angular module with rollup.js: external html template file won't work (404)


I'm developing an Angular lib (GitHub repo link), there are

  • lib module sources placed at ./src
  • test App sources placed at ./app
  • lib distributive at ./dist

The build process uses rollup.js and is based on angular-library-starter. I also have a process that generates npm package from ./dist and installs it to ./node_modules. The issue is that the App works fine with the lib module imported from ./src and does not work when I imported it from ./dist or ./node_modules:

// ./app/app/app.module.ts
import { AppComponent } from './app.component';
import { UiScrollModule } from '../../src/ngx-ui-scroll';   // works
//import { UiScrollModule } from 'ngx-ui-scroll';           // doesn't work
//import { UiScrollModule } from '../../dist/bundles/ngx-ui-scroll.umd.js'; // no...

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, UiScrollModule],
  bootstrap: [AppComponent]
})
export class AppModule { }

There are no errors during build process, but the browser console says (for both of ./dist and ./node_modules importing cases):

GET http://localhost:4200/ui-scroll.component.html 404 (Not Found)
Failed to load ui-scroll.component.html

And it is true that my lib module has a component which has an external temlate:

// ./src/component/ui-scroll.component.ts
@Component({
  selector: 'app-ui-scroll',
  templateUrl: './ui-scroll.component.html'
})
export class UiScrollComponent implements OnInit, OnDestroy { /* ... */ }

If I would inline the template (using template instead of templateUrl in the @Component settings), it will work, I tested it. But I want the template to be in separate file... I believe this is a build process responsibility. There are a bunch of configs related to my build process, I think it's not a good idea to list them all here. They could be found at the lib repository (or I can post any exact parts by request).

Has anyone encountered the problem of an external html template rollup-bundling?


Solution

  • I believe this is a build process responsibility.

    Seems you're right. We usually inline template during the build process.

    In order to do you can create js file like:

    /utils/inline-resouces.js

    const {dirname, join} = require('path');
    const {readFileSync, writeFileSync} = require('fs');
    const glob = require('glob');
    
    /** Finds all JavaScript files in a directory and inlines all resources of Angular components. */
    module.exports = function inlineResourcesForDirectory(folderPath) {
      glob.sync(join(folderPath, '**/*.js')).forEach(filePath => inlineResources(filePath));
    };
    
    /** Inlines the external resources of Angular components of a file. */
    function inlineResources(filePath) {
      let fileContent = readFileSync(filePath, 'utf-8');
    
      fileContent = inlineTemplate(fileContent, filePath);
      fileContent = inlineStyles(fileContent, filePath);
    
      writeFileSync(filePath, fileContent, 'utf-8');
    }
    
    /** Inlines the templates of Angular components for a specified source file. */
    function inlineTemplate(fileContent, filePath) {
      return fileContent.replace(/templateUrl:\s*'([^']+?\.html)'/g, (_match, templateUrl) => {
        const templatePath = join(dirname(filePath), templateUrl);
        const templateContent = loadResourceFile(templatePath);
    
        return `template: "${templateContent}"`;
      });
    }
    
    /** Inlines the external styles of Angular components for a specified source file. */
    function inlineStyles(fileContent, filePath) {
      return fileContent.replace(/styleUrls:\s*(\[[\s\S]*?])/gm, (_match, styleUrlsValue) => {
        // The RegExp matches the array of external style files. This is a string right now and
        // can to be parsed using the `eval` method. The value looks like "['AAA.css', 'BBB.css']"
        const styleUrls = eval(styleUrlsValue);
    
        const styleContents = styleUrls
          .map(url => join(dirname(filePath), url))
          .map(path => loadResourceFile(path));
    
        return `styles: ["${styleContents.join(' ')}"]`;
      });
    }
    
    /** Loads the specified resource file and drops line-breaks of the content. */
    function loadResourceFile(filePath) {
      return readFileSync(
          filePath.replace('dist\\package\\esm5\\', '').replace('dist\\', ''), 'utf-8')
        .replace(/([\n\r]\s*)+/gm, ' ')
        .replace(/"/g, '\\"');
    }
    

    and then change your build.js file as follows:

    build.js

    ...
    const ESM5_DIR = `${NPM_DIR}/esm5`;
    const BUNDLES_DIR = `${NPM_DIR}/bundles`;
    const OUT_DIR_ESM5 = `${NPM_DIR}/package/esm5`;
    
    // 1) import function from created above file
    const inlineResourcesForDirectory = require('./utils/inline-resources');
    // 1) end
    
    ...
    
    /* AoT compilation */
    shell.echo(`Start AoT compilation`);
    if (shell.exec(`ngc -p tsconfig-build.json`).code !== 0) {
      shell.echo(chalk.red(`Error: AoT compilation failed`));
      shell.exit(1);
    }
    shell.echo(chalk.green(`AoT compilation completed`));
    
    // 2) Inline template after first ngc build
    shell.echo(`Start inlining templates in ${NPM_DIR} folder`);
    inlineResourcesForDirectory(NPM_DIR);
    shell.echo(`Inlining templates in ${NPM_DIR} folder completed`);
    // 2) end
    
    ...
    
    shell.echo(`Produce ESM5 version`);
    shell.exec(`ngc -p tsconfig-build.json --target es5 -d false --outDir ${OUT_DIR_ESM5} --importHelpers true --sourceMap`);
    
    // 3) Inline template after second ngc build
    shell.echo(`Start inlining templates in ${OUT_DIR_ESM5} folder`);
    inlineResourcesForDirectory(OUT_DIR_ESM5);
    shell.echo(`Inlining templates in ${OUT_DIR_ESM5} folder completed`);
    // 3) end
    
    if (shell.exec(`rollup -c rollup.es.config.js -i ${OUT_DIR_ESM5}/${PACKAGE}.js -o ${ESM5_DIR}/${PACKAGE}.js`).code !== 0) {
    

    After all 3 changes above you can check for example your ngx-ui-scroll.umd.js bundle. It should look like:

    enter image description here

    See also