0

Case I: I have a file called data.json

{
  "a": 1,
  "b": 2,
  ...
}

Which I imported/required in index.js as shown below

import data from './data.json';

console.log(data["a"]);

Everything works fine but the whole data.json is dumped into index.js when bundled with webpack hence file size increased with property values I don't need.

Case II: However, if I do the following in index.js

const a = {
  "a": 1,
  "b": 2,
  ...
}

console.log(data["a"]);

Everything is fine (The value 1 get logged) and no unnecessary properties of the json variable a were dumped. I think webpack's Tree Shaking is working here (I'm not sure)

My Question: How can I achieve case II (no unnecessary properties) by requiring/importing the file like it's done in case I?

I was thinking if there's a way to treat the content of require as a value and not a dependency so webpack or any other bundler doesn't include it in the bundled file.

PS: I'm bundling for WEB

Ramin eghbalian
  • 2,348
  • 1
  • 16
  • 36
Toheeb
  • 13
  • 4
  • 1
    Don't use json, and just export an object.. `export const data = {a:1, b:2}` ps. case II is not JSON. – Keith Feb 25 '20 at 15:34
  • Thank you @Keith, that worked! I exported as you said (as js file) then ```import {data} from './data.js';``` Would you like to make this an answer so I can accept. – Toheeb Feb 25 '20 at 17:04

1 Answers1

0

Edit: Sorry, didn't read properly.

Include a JSON file as Webpack output, but not part of bundle.js

I think this is what you are looking for.

Dylan's solution is very nice too, but I prefer simply: Edited out code..

  • This isn't about loading a JSON file, OP knows how to do that. Please re-read the question. –  Feb 25 '20 at 15:44
  • Alright, then it's a possible duplicate of https://stackoverflow.com/questions/38959329/include-a-json-file-as-webpack-output-but-not-part-of-bundle-js – Tibor Szűcs Feb 25 '20 at 15:52
  • Thanks ChrisG and everyone else. @keith's comment worked out for me – Toheeb Feb 25 '20 at 17:07