Load dynamic file content as string

24 views Asked by At

I'm going crazy! I'm using Vue2 with Vuetify and I need to open some modals with simple guidelines for the current page. This guidelines are stored in a folder as .txt files in the form filename.lang.txt. The problem is "lang" because makes the name of the file dynamic. Shortly:

This is my webpack configuration (vue.config.js)

const fs = require("fs");

module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.ico$/,
          use: {
            loader: "file-loader",
            options: {
              context: "src/assets"
            }
          }
        },
        {
          exclude: /node_modules/,
          test: /\.txt$/,
          use: {
            loader: "raw-loader"
          }
        }
      ]
    },
    output: {
      filename: "[name].[hash].bundle.js"
    }
  },
  devServer: {
    cert: fs.readFileSync("certs/bc.test.com.pem"),
    host: "bc.test.com",
    key: fs.readFileSync("certs/bc.test.com-key.pem"),
    port: 10000
  },
  pages: {
    index: {
      entry: "src/main.js",
      title: "Business Suite"
    }
  },
  productionSourceMap: false,
  transpileDependencies: ["vuetify"]
};

Then in a file js that wraps my common functions, I wrote this

function getTxtFileContent(path, fileBaseName) {
  const lang = getLang(); // "it" in this example
  let fileName = `${fileBaseName}.${lang}.txt`;

  path = "@" + (path.charAt(0) == "/" ? "" : "/") + path;
  path = path + (path.charAt(path.length - 1) == "/" ? "" : "/") + fileName;

  const fileContent = require(path).default;
  // const fileContent = require("!!raw-loader!@/modules/cp/files/calendarGuide.it.txt").default;
  console.log(fileContent);

  return fileContent;
}

Now, if I comment all the code that build the path and ask for the file with the plain sting path everithing goes well, but if I run this code (with dynamic path) I get this error:

[Vue warn]: Error in v-on handler: "Error: Cannot find module '@/modules/cp/files/calendarGuide.it.txt'"

I have tried prefixing with raw-loade! and !!raw-loader! and changed the wildcard '@' with src, .. and ./.. but nothing changes!

Surely some of you have already needed to read the contents of dynamic files in your life, so, any suggestion?

This is a new feature in the project and I start to use raw-loader after internet searching but it is not required, I can drop all if needed and start with other solutions.

Thanks

0

There are 0 answers