简体   繁体   English

如何在 Angular 7 中配置 raw-loader 来加载文本文件?

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

I want to use a raw-loader with my Angular 7 to import text files into my TypeScript source code.我想在我的 Angular 7 中使用原始加载器将文本文件导入我的 TypeScript 源代码。 I've found plenty of information on the subject and spent a few hours trying to get it to work, but I can not get it to work.我找到了很多关于这个主题的信息,并花了几个小时试图让它工作,但我无法让它工作。

I start by creating a new project我首先创建一个新项目

ng new example --defaults --minimal

I create a text file at /src/app/example.txt with the message "Hello World"我在/src/app/example.txt中创建了一个文本文件,其中包含消息“Hello World”

I then modify the app.component.ts file to import this text file.然后我修改app.component.ts文件以导入此文本文件。

import {Component} from '@angular/core';
import str from 'example.txt';

alert(str);

@Component({
    selector: 'app-root',
    template: ``,
    styles: []
})
export class AppComponent {
}

I see a Cannot load module "example.txt" error in WebStorm, and when I run ng build and I get the following error.我在 WebStorm 中看到Cannot load module "example.txt"错误,当我运行ng build时出现以下错误。

ERROR in src/app/app.component.ts(2,17): error TS2307: Cannot find module 'example.txt' src/app/app.component.ts(2,17) 中的错误:错误 TS2307:找不到模块“example.txt”

So I Googled how to resolve this issue and I found this answer.所以我用谷歌搜索了如何解决这个问题,我找到了这个答案。

How to import JSON File into a TypeScript file? 如何将 JSON 文件导入 TypeScript 文件?

I then add a /src/typings.d.ts file with the following contents, and this fixes the error in WebStorm.然后我添加一个包含以下内容的/src/typings.d.ts文件,这修复了 WebStorm 中的错误。

declare module "*.txt" {
    const value: string;
    export default value;
}

I run ng build again and the error message changes to say it can't find the module.我再次运行ng build ,错误消息变为找不到模块。

Module not found: Error: Can't resolve 'example.txt' in 'C:\work\temp\example\src\app'找不到模块:错误:无法解析“C:\work\temp\example\src\app”中的“example.txt”

After some lengthy Googling, I figure that I need to add a raw-loader to Angular using a custom webpack configuration.经过长时间的谷歌搜索后,我认为我需要使用自定义 webpack 配置向 Angular 添加一个原始加载器。 Which leads me to this blog post with instructions.这让我看到了这篇带有说明的博文。

https://codeburst.io/customizing-angular-cli-6-build-an-alternative-to-ng-eject-a48304cd3b21 https://codeburst.io/customizing-angular-cli-6-build-an-alternative-to-ng-eject-a48304cd3b21

So I install custom-webpack所以我安装了 custom-webpack

npm i -D @angular-builders/custom-webpack

I edit my angular.json so that the build uses extra-webpack.config.js like so.我编辑我的angular.json以便构建像这样使用extra-webpack.config.js

          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./extra-webpack.config.js"
            },

I create the extra-webpack.config.js in the same folder as angular.json with the following contents.我在与 angular.json 相同的文件夹中创建了extra-webpack.config.js angular.json内容如下。

module.exports = {
    module: {
        rules: [
            {
                test: /\.txt$/,
                use: 'raw-loader'
            }
        ]
    }
};

I try building again ng build but get the same error.我尝试再次ng build但得到相同的错误。

Module not found: Error: Can't resolve 'example.txt' in 'C:\work\temp\example\src\app'找不到模块:错误:无法解析“C:\work\temp\example\src\app”中的“example.txt”

I have been unable to get past this point, and everything I've Googled so far seems to imply that this is how it's supposed to be done.我一直无法超越这一点,到目前为止我用谷歌搜索过的所有内容似乎都暗示这就是应该如何完成的。 Module not found error messages are very broad and I can not find anything specific to Angular 7. Module not found错误消息非常广泛,我找不到任何特定于 Angular 7 的内容。

I figured it out, and the answer was on the raw-loader documentation page.我想通了,答案在 raw-loader 文档页面上。 At the bottom it explains that you have to prefix the import path with raw-loader!在底部,它解释说您必须在导入路径前加上raw-loader!

https://webpack.js.org/loaders/raw-loader/#examples 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.你必须弄清楚如何让 TypeScript 识别模块,然后你必须配置 Angular 以使用加载程序,然后你必须知道如何正确导入文件。

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.谷歌搜索结果中没有一个显示与 Angular 7 相关的所有内容。所以我发现这出现在其他人的搜索结果中。

Working in Angular 9,10 with Ivy使用 Ivy 在 Angular 9,10 中工作

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更改angular.json以使用@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 file webpack.partial.js next to angular.jsonwebpack.partial.js旁边添加文件angular.json
module.exports = {
  module: {
    rules: [
      { test: /\.(txt|md)$/, loader: 'raw-loader' }
    ]
  } 
};
  1. add type declaration in file ./types/textfile.d.ts在文件./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确保你的tsconfig文件知道textfile.d.ts
{
  "compilerOptions": {
...
    "typeRoots": ["node_modules/@types", "./types"],
...                                       // ^ this is important
}
  1. import your text files using require syntax使用require语法导入文本文件
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. Done, The project should serve/build in angular 9,10 now完成,该项目现在应该以角度 9,10 服务/构建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在从raw-loader导入文本并使用showdown格式化时保留VueJS中的换行符 - How to preserve newlines in VueJS when importing text from raw-loader and formatted using showdown 尝试使用raw-loader加载svg时出现包错误 - getting bundle error when trying to load svg with raw-loader Webpack - 找不到模块 raw-loader - Webpack - Cannot find module raw-loader 在主项目文件夹之外测试角度组件:未找到模块原始加载器 - Testing angular components outside of main project folder: module not found raw-loader 如何在 vue 中使用 raw-loader,在 scss 中使用 file-loader - How can I use raw-loader in vue, and file-loader in scss 使用 webpacks raw-loader 读取 markdown 文件会导致 index.html 的内容 - Using webpacks raw-loader to read markdown files results in contents of index.html 如何从Webpack的Raw-loader中排除html-webpack-plugin模板 - How to exclude html-webpack-plugin templates from raw-loader in webpack 如何借助 raw-loader 在 vue 组件中导入和使用 bpmn 文件 - How to import and use bpmn file in vue component with aid of raw-loader 最新的raw-loader版本在webpack配置中不起作用。 怎么解决? - Latest raw-loader version is not working in webpack config. How to fix it? Webpack raw-loader 在需要 markdown 文件时出错 - Webpack raw-loader errors out when require markdown file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM