I am struggling to implement a raw-loader with my Angular 7 in order to import text files into my TypeScript source code. Despite spending several hours researching and attempting various methods, I have been unsuccessful in getting it to work.
My journey begins by creating a new project
ng new example --defaults --minimal
After creating a text file at /src/app/example.txt
containing the message "Hello World"
I proceed to modify the app.component.ts
file to import this text file.
import {Component} from '@angular/core';
import str from 'example.txt';
alert(str);
@Component({
selector: 'app-root',
template: ``,
styles: []
})
export class AppComponent {
}
Encountering a Cannot load module "example.txt"
error in WebStorm, along with an error after running ng build
.
ERROR in src/app/app.component.ts(2,17): error TS2307: Cannot find module 'example.txt'
Seeking solutions online, I came across an answer which suggested creating a /src/typings.d.ts
file with specific contents to resolve the issue in WebStorm.
declare module "*.txt" {
const value: string;
export default value;
}
However, upon another attempt of running ng build
, a different error surfaced.
Module not found: Error: Can't resolve 'example.txt' in 'C:\work\temp\example\src\app'
To move forward, I delved into adding a raw-loader to Angular using a custom webpack configuration, as detailed in a blog post.
https://codeburst.io/customizing-angular-cli-6-build-an-alternative-to-ng-eject-a48304cd3b21
Consequently, I installed custom-webpack
npm i -D @angular-builders/custom-webpack
Proceeded to edit my angular.json
to incorporate extra-webpack.config.js
in the build process.
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./extra-webpack.config.js"
},
Including the creation of extra-webpack.config.js
file following certain specifications.
module.exports = {
module: {
rules: [
{
test: /\.txt$/,
use: 'raw-loader'
}
]
}
};
Even after trying to rebuild using ng build
, the same error persisted.
Module not found: Error: Can't resolve 'example.txt' in 'C:\work\temp\example\src\app'
Despite extensive research, I remain stuck at this juncture with no concrete answers tied specifically to Angular 7's Module not found
error messages.