3

I'm trying to use Webpack file-loader to copy a static json resource file to dist/ so I can import that json file in a Vue.js component. Webpack is copying the file correctly when I run npm run build, but when I try to import the file (like import myJson from '@/static/runtimeConfig.json') then "myJSON" variable only gets the file path instead of the actual JSON file contents. Can anyone help me understand why this is?

My webpack file-loader config looks like this:

module: {
      //load runtimeConfig.json file through a custom loader
      rules: [
        {
          // set the type to javascript/auto to bypass webpack's built-in json importing
          type: 'javascript/auto',
          test: /(runtimeConfig\.json)$/i,
          // file-loader resolves imports on a file and emits that file to dist/
          loader: 'file-loader',
          // use filename runtimeConfig.json instead of a hashed filename
          options: {
            name: '[path][name].[ext]',
            outputPath: 'static',
          }
        }
      ],
    },

My intent is to import a json file in a vue.js components, like this:

import myJson from '@/static/runtimeConfig.json'

But, after I do that import, myJson is just the path to the file, not the actual json contents

console.log(myJson)
--> /static/src/static/runtimeConfig.json

1 Answer 1

2

That's exactly what file-loader does - it copies the file into dist and returns path to a file. Because its primarily used to process content of img href attributes. Now you can load it onto your running app at runtime by ajax request using the path provided...

If you just want to include JSON file into your app as an object, you can just import it without any Webpack configuration and it will be imported as JS object and included in your JS bundle. This happens at build time

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. I was hoping to do an import instead of an HTTP GET, but I think I must have to do HTTP GET. The import approach seems to only work at build time. Since I'll be changing the JSON file at runtime, I don't want it to get compiled in during build time.
Yes, import is build time thing. So you must do multiple builds for each different runtimeConfig.json. But loading the file at runtime by Ajax call slows your app down (waiting for a request). Its your choice...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.