'Read a file content as a string in Vue

Some other post respond to the same problem (here, here and here) by using raw-loader but from my understanding it is deprecated for webpack v5 (but I'm not sure if it's relevant for Vue).

Also when I tried using it my file got loaded as a path : for example doing import file from '/src/assets/article.txt' creates a variable named 'file' containing the path as a String.



Solution 1:[1]

You're right raw-loader has been deprecated in Webpack 5. You should use Asset Modules instead.

Asset Modules type replaces all of these loaders by adding 4 new module types:

  • asset/source exports the source code of the asset. Previously achievable by using raw-loader.

Here is an example of the vue.config.js:

module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {       
         test: /\.txt/,
         type: 'asset/source',
        }
      ]
    },
  }
}

I tested it on a vanilla Vue 3 project installed with Vue CLI. It worked perfectly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1