How to configure raw-loader in Angular 7 to load text files?

后端 未结 2 1404
忘掉有多难
忘掉有多难 2020-12-16 02:06

I want to use a raw-loader with my Angular 7 to import text files into my TypeScript source code. I\'ve found plenty of information on the subject and spent a few hours tryi

2条回答
  •  死守一世寂寞
    2020-12-16 02:12

    Working in Angular 9,10 with Ivy

    So I finally got it working, from this comment on an issue, here's the steps I took, if anyone else is looking for help.

    1. yarn add -D @angular-builders/custom-webpack raw-loader

    2. Change angular.json to use @angular-builders/custom-webpack

    ...
    "architect": {
      "build": {
        "builder": "@angular-builders/custom-webpack:browser",
        "options": {
          "customWebpackConfig": {
            "path": "./webpack.partial.js"
          },
      ...
      "build": {
        "builder": "@angular-builders/custom-webpack:dev-server",
        "options": {
          "browserTarget": "PROJECTNAME:build"
        },
      ...
    
    1. add file webpack.partial.js next to angular.json
    module.exports = {
      module: {
        rules: [
          { test: /\.(txt|md)$/, loader: 'raw-loader' }
        ]
      } 
    };
    
    1. add type declaration in file ./types/textfile.d.ts
    declare module '!raw-loader!*' {
      const contents: string;
      export = contents;
    }
    
    1. make sure that your tsconfig file knows about textfile.d.ts
    {
      "compilerOptions": {
    ...
        "typeRoots": ["node_modules/@types", "./types"],
    ...                                       // ^ this is important
    }
    
    1. import your text files using require syntax
    import { Component } from '@angular/core';
    
    const myText = require('!raw-loader!./my-text-file.txt');
    
    @Component({
      template: `
    {{myText}}
    `, }) export class ChangeLogComponent { myText = myText; }
    1. Done! The project should serve/build in angular 9,10 now

提交回复
热议问题