Ilja
Ilja

Reputation: 46479

Is there any way to import files / constants into a json file

In my component I want to include a json file of data, so think

import slides from './slides-data.json'

and slides-data.json looks something like

{
  "slides": [
    { img: "img.png", "text": "some text" },
    ...
  ]
}

ideally though I would like to import images into a json file like so

import MyImage from './assets/img.png'
{
  "slides": [
    { img: "img.png", "text": "some text" },
    ...
  ]
}

this is not a valid json, but I am using webpack to handle loaders and was wondering if something like this is possible?

Upvotes: 2

Views: 2291

Answers (1)

Bob  Sponge
Bob Sponge

Reputation: 4738

You can write own loader for slides-data.json (just example, not tested):

module.exports = function(source) {
    this.cacheable();
    JSON.parse(source).slides.forEach(function(slide) {
        this.addDependency(slide.img); // need to resolve this path before adding as dependency
    });
    return source;
};

and add loader in config:

{test: /slides-data\.json$/, loader: "json-loader!your-custom-slides-loader"}

Also you can use own file extension for slides-data.json.


But firstly check out these links:

How to write a loader

Loaders API

Upvotes: 1

Related Questions