如何将文件导入使用create react app作为原始文本的react app中? [英] How to import a file into a react app that uses create react app as raw text?

查看:79
本文介绍了如何将文件导入使用create react app作为原始文本的react app中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我想显示一些代码以供项目本身参考.
  2. 我希望代码的显示随实现而更新.
  3. 我不想从 create-react-app
  4. 中退出

这个用 create-react-app 和打字稿创建的react项目将用于显示一些自定义组件,以便在其他项目中重复使用.我的目标是在使用该组件的代码旁边使用该组件.

This react project, created with create-react-app and typescript, is going to be used to display some custom components for re-use in other projects. My goal is to have the component be used right next to the code that is using it.

如果我无权访问webpack配置并且不能使用 fs.readFile ,该如何加载文件?

How can I load the file if I don't have access to the webpack config, and I can't use fs.readFile?

推荐答案

环顾四周后,我设法使它正常工作.要使其正常工作,必须准备两个主要部分.

I managed to get this working after a bit of looking around. There are two major pieces that had to be in place to make it work.

在这种情况下,我想使用 raw-loader ,因此我将其安装为dev依赖项. yarn add -D raw-loader .

In this case I wanted to use the raw-loader, so I installed it as a dev dependency. yarn add -D raw-loader.

为了真正导入文件,我需要重写如下所示的webpack配置:

In order to actually import the file I needed to then override the webpack configuration like this:

// eslint-disable-next-line import/no-webpack-loader-syntax
import toolbarItems from '!!raw-loader!../ToolbarItems';

这会将整个文件加载到变量toolbarItems中.通过在加载器之前使用 !! ,我可以防止任何其他Webpack加载器在这种特定情况下对其进行处理.这可能可以在普通的javascript项目中单独运行,但可以在打字稿中...

This loads the entire file into the variable toolbarItems. By using the !! before the loader I prevent any other webpack loaders from processing it in this specific case. This might work on its own in a plain javascript project, but in typescript...

我遇到打字稿错误:

Failed to compile.

/Users/cory/Code/something/custom-theme/src/pages/NavigationDemo.tsx
TypeScript error in /Users/cory/Code/something/custom-theme/src/pages/NavigationDemo.tsx(9,26):
Cannot find module '!!raw-loader!../ToolbarItems'.  TS2307

     7 |
     8 | // eslint-disable-next-line import/no-webpack-loader-syntax
  >  9 | import toolbarItems from '!!raw-loader!../ToolbarItems';
       |                          ^
    10 |
    11 | const useStyles = makeStyles({
    12 |   root: {

只需在名为 ToolbarItems.ts.d.ts 的文件中声明用于加载程序的模块,即可为我解决此问题:

Simply declaring a module for the loader in a file called ToolbarItems.ts.d.ts solved the issue for me:

declare module '!raw-loader!*' {
  const content: string;
  export default content;
}

来源

这篇关于如何将文件导入使用create react app作为原始文本的react app中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆