Importing text file as string in Vue Cli 3

In my assets folder, I have a plain text file called “helloworld.txt” which contains “Hello World.” I want to import helloworld.txt as a string in Javascript in one of my Vue components so I can display it on screen. What’s the best way to do this? Ideally I’d like to be able to do something like

import helloworld from './assets/helloworld.txt';

but that leaves helloworld as an empty object.
I’m using the Babel plugin for vue-cli.

you should porbably add raw-loader for the .txt extension to your webpack config, or do it inline like:

ìmport helloworld from 'raw-loader!./assets/helloworld.txt'

4 Likes

Thanks, the inline solution did what I needed it to.

For any future readers of this thread, I also had to install raw-loader using npm, by running

npm install raw-loader --save-dev

in the main directory of the project.

Also of note, if the file is something that would be parsed with something other than raw-loader, you can put another “!” before “raw-loader” to get it to only parse with raw-loader, like so:

ìmport helloworld from '!raw-loader!./assets/helloworld.txt'

This was relevant because I was trying to load a javascript file as plain text, and it was including polyfill imports in the plain text.

1 Like

Additionally: If you only have small portions of text , which could fit into a variable,
you could leverage .env-Files.

Docs

1 Like

Just a quick note if, like me, you copy-pasted the above lines and got errors: “import” is misspelled, the i in the code above is a letter i with a downwards accent.

ìmport
import

If you’re using TypeScript and keep getting errors like this:

Cannot find module 'raw-loader!./assets/helloworld.txt'.

Then you need to add this somewhere:

declare module 'raw-loader!*'

In my case I created a file global.d.ts in the project root.

Hi~

I have installed raw-loader in my main directory, but when I was trying to use

import helloworld from 'raw-loader!./assets/helloworld.txt'

error occurs.

Am I supposed to configure some files like webpack or babel? But I am so confused with these configurations.

1 Like

Same issue here.