How to configure raw-loader in Angular 7 to load text files?
I figured it out, and the answer was on the raw-loader documentation page. At the bottom it explains that you have to prefix the import path with raw-loader!
https://webpack.js.org/loaders/raw-loader/#examples
import {Component} from '@angular/core';
import str from 'raw-loader!./example.txt';
alert(str);
@Component({
selector: 'app-root',
template: ``,
styles: []
})
export class AppComponent {
}
I found this very difficult to figure out. You have to figure out how to get TypeScript to recognise the modules, then you have to configure Angular to use the loader and then you have to know how to correctly import the file.
None of the Google search results showed everything together as it related to Angular 7. So I found this turns up in search results for other people.
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.
yarn add -D @angular-builders/custom-webpack raw-loader
Change
angular.json
to use@angular-builders/custom-webpack
...
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./webpack.partial.js"
},
...
"serve": {
"builder": "@angular-builders/custom-webpack:dev-server",
"options": {
"browserTarget": "PROJECTNAME:build"
},
...
- add file
webpack.partial.js
next toangular.json
module.exports = {
module: {
rules: [
{ test: /\.(txt|md)$/, loader: 'raw-loader' }
]
}
};
- add type declaration in file
./types/textfile.d.ts
declare module '!raw-loader!*' {
const contents: string;
export = contents;
}
- make sure that your
tsconfig
file knows abouttextfile.d.ts
{
"compilerOptions": {
...
"typeRoots": ["node_modules/@types", "./types"],
... // ^ this is important
}
- import your text files using require syntax
import { Component } from '@angular/core';
const myText = require('!raw-loader!./my-text-file.txt');
@Component({
template: `<pre>{{myText}}</pre>`,
})
export class ChangeLogComponent {
myText = myText;
}
- Done! The project should serve/build in angular 9,10 now