Wednesday 17 May 2017

Loading a static file in Angular during build

I'm want to load the contents of a file and inject it as a string in TypeScript at build time. I understand that this code would ordinarily be server code, but what I want is to have a build step that reads the file and injects its contents as a string.

import { readFileSync } from 'fs';
import { Component } from '@angular/core';

@Component({
  template: `<pre>${readFileSync('./example.code')}</pre>`
})
export class ExampleComponent { }

Assuming example.code just has "Hello World" I would want this file to be built as:

template: `<pre>"Hello World"</pre>`

I have found babel-plugin-static-fs which I think should allow me to do this, but I was originally using ng (angular-cli) to build the project. I have done ng eject and updated webpack:

module: {
  rules: [
    /* snip */
    {
      "test": /\.ts$/,
      "use": [
        {
          loader: "babel-loader",
          options: {
            plugins: ['babel-plugin-static-fs']
          }
        },
        {
          "loader": "@ngtools/webpack"
        }, ] } ] }

However, when I run webpack, I still get

Cannot find module 'fs'

If I reverse the order of the loaders, it seems like babael does not like the @ used in may annotations such as the @Component above so that loader does not work.

Is there any way to load a file as static content during an Angular project build?



via Explosion Pills

No comments:

Post a Comment