Setting up raw-loader in Angular 7 for loading text files

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 founderror messages.

Answer №1

After some investigation, I finally cracked the code and discovered the solution on the raw-loader documentation page. It turns out that you need 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 {
}

Figuring this out was quite challenging. First, you must ensure TypeScript recognizes the modules, then configure Angular to use the loader, and accurately import the file.

None of the Google search results provided a comprehensive guide as it relates to Angular 7. Therefore, I hope this information helps others who encounter similar obstacles in their searches.

Answer №2

Configuring Angular 9 and 10 with Ivy

After much trial and error, I finally managed to get everything working smoothly by following the steps outlined in this helpful comment on an issue. For anyone else struggling with this, here's what worked for me:

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

  2. Update angular.json to utilize @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"
    },
  ...
  1. Add a file named webpack.partial.js next to your angular.json
module.exports = {
  module: {
    rules: [
      { test: /\.(txt|md)$/, loader: 'raw-loader' }
    ]
  } 
};
  1. Add type declaration within the file ./types/textfile.d.ts
declare module '!raw-loader!*' {
  const contents: string;
  export = contents;
}
  1. Ensure that your tsconfig file is aware of textfile.d.ts
{
  "compilerOptions": {
...
    "typeRoots": ["node_modules/@types", "./types"],
...                                     // ^ don't forget this
}
  1. Import your text files using the 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;
}
  1. And there you have it! Your project should now serve and build correctly in Angular 9 and 10 with Ivy

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing an http.get request in Angular2 without using RxJS

Is there a method to retrieve data in Angular 2 without using Observable and Response dependencies within the service? I believe it's unnecessary for just one straightforward request. ...

How can I create a parent div with cursor-pointer and apply inline styling to make all child elements

Is there a way to apply the cursor-pointer style to an entire div with inline CSS without it affecting just the white space around the child elements? I have tried using position and z-index without success. I am unable to use an external stylesheet for t ...

Express: utilizing rawBody or buffer for a specific endpoint

I am looking to access the rawBody (buffer) specifically for a POST request on one route within my application. Currently, I have the following code snippet in my app.js: app.use(bodyParser.json({ verify: function(req, res, buf) { req.rawBody = buf; }})) ...

Which file should I include in the .gitignore, jsconfig.json or tsconfig.json?

When working on a project, the utilization of a jsconfig file is required. The jsconfig file typically appears as follows: { "compilerOptions": { "baseUrl": ".", "paths": { "*": [ "src/*" ], ...

JavaScript Intercept Paste function allows you to detect and capture data being past

I stumbled upon this code snippet while browsing through how to intercept paste event in JavaScript. The code works well for intercepting clipboard data before it's pasted, ensuring that essential "\n" characters are not lost during the process. ...

PayPal's Intelligent Payment Buttons: Oops! There seems to be an issue with parsing the JSON data - an unexpected character was found at line 1,

I've been racking my brain over this issue for the past two days... I've been attempting to integrate Smart Payment Buttons from PayPal, diligently following each step in the guide. However, I keep encountering the following error: Error: JSON. ...

Ways to Ensure a Property of an Object Remains Synced with Another

I'm dealing with the following Object structure: { a: "123" b: "$a" } In this setup, b should always be equal to the value of a. Any suggestions on how I can achieve this using JavaScript? ...

Using the Selenium webdriver to reach the bottom of the page by scrolling vertically

Is there a way to determine if I have scrolled to the bottom of the page vertically? I have been using Webdriver and pressing the page down key repeatedly within a for loop, like so: for(int di=0; di<40; di++) { driver.findElement(By.tagName("body ...

Is there a way to modify an element in an array in AngularJS without using splice?

I encountered a situation similar to the one described in this post here, where I not only want to retrieve an element but also change its name value. I came across a method that involves using splice: dataList.splice(index, 1); dataList.splice(index, 0, ...

Best practices for handling http requests in each individual route of AngularJs

Just starting out with AngularJs and attempting to set up multiple routes with different $http requests. I'm facing an issue where the page content loads late after a route change. I've come up with a workaround, but I feel like there might be a ...

dynamically filter a set of string elements

Is there a way to dynamically filter a list of strings? I have come across examples using ng-repeat, but it seems that it does not work with angular 7: it does not load any strings, only works with ngFor <div class="input-group"> <div class="i ...

Is there a way to generate random numbers that will create a chart with a general upward trend?

Are you looking for a solution to generate random numbers for charts that trend upwards and to the right? I am currently utilizing a JavaScript charting engine, so I will require numbers in JSON format eventually. However, I am open to alternative methods ...

Node.js is unable to handle the contents of an SNS event message

I am encountering an issue while attempting to extract content from a Message in an SNS event within a Node.js Lambda project Below is the code snippet for processing the message: exports.handler = (event, context, callback) => { var message = event. ...

What is the best way to delete markers from a leaflet map?

I need to remove markers from my map. I am looking to create a function that will specifically clear a marker based on its ID. I am utilizing Leaflet for the map implementation. Here is my function: public clearMarkers(): void { for (var id in this. ...

Complete interaction with child processes in Node.js

I have a basic C++ program compiled using the command gcc 1.cpp -o 1.exe. // 1.cpp #include <stdio.h> int main(){ int num = 0; scanf("%d", &num); printf("%d", num + 1000); scanf("%d", &num); printf("\n%d", num + 1000); ...

Unable to locate the specified CSS file

I've been diving into the world of NativeScript and exploring the tutorials provided at . However, I'm facing an issue with getting the platform specific CSS to work properly. Every time I try to run the code, I encounter the following error mess ...

"ModuleNotFound" error occurred when attempting to utilize Netlify lambda functions with external dependencies

https://i.stack.imgur.com/vVmky.jpg I'm currently exploring the capabilities of Netlify, specifically its lambda function feature for running a node function with dependencies. Following a tutorial from CSS-Tricks, my functions/submission-created.js ...

Keep the active button state when it is clicked in React JS within a functional component

When I click on a button, I want to remain in the section while also having the button stay in the background with a color that indicates my selection. This could be for breakfast, lunch, dinner, or any other section. const Categories = ({ categories, fi ...

Node.js readline: SyntaxError: Unexpected token =>

Currently, I am diving into node.js and have found myself in need of utilizing the readline module for a new project. Below is the code snippet that I extracted directly from the official readline module example. const readline = require('readline&ap ...

The program experienced an issue with TypeError: Attempting to access properties of an undefined variable ('_id')

I am attempting to show a data entry (with a unique id) in Angular, but I'm encountering the following error: ERROR TypeError: Cannot read properties of undefined (reading '_id') The service for retrieving the specific id is defined as: g ...