2

I have a webpack app that I'd like to read a json file in at runtime.

After webpack packages the application, I'd like the json file to be excluded from the bundle.js but still in the package folder. How can I do this?

David Small
  • 581
  • 1
  • 10
  • 25
  • 1
    Same as you would use an image : http://stackoverflow.com/questions/27639005/how-to-copy-static-files-to-build-directory-with-webpack with file-loader. – Boris Charpentier Aug 15 '16 at 16:53

2 Answers2

3

I'd use copy-webpack-plugin

Pretty simply moves files from one location to another

You moved the json file into the destination package by passing it an object:

{ from: 'source', to: 'dest' }

Checkout the repo for usage examples

j-d-b
  • 51
  • 4
1

Use the file-loader which will let you specify an output file. Not the cleanest, since webpack really really wants to bundle everything, but it works.

require('file?name=../newfile.json!/somefolder/original.json');

The above will create newfile.json a directory above your webpack output folder. (Folder change for illustration purposes; not required.)

If you want to re-require the json*, mark it as an external dependency in the webpack config and use `require('../newfile.json').

*I'd suggest using a regular ajax call to pull the json in though. That way it's clear that the json is an external and you won't have to go through webpack's ajax system.

Quotidian
  • 2,870
  • 2
  • 24
  • 19
  • If I use var jsonData = require('../pageJSON/page.json'); and console log it, I get /aac68c8f2642e163fd998c4c012d0d14.json – David Small Aug 15 '16 at 17:22
  • 1
    The `name` part is the important bit. That tells webpack what to name the output file. (Otherwise it's included in the bundle like a normal loader's output.) – Quotidian Aug 15 '16 at 17:24
  • The issue is that I want the var jsonData to be the json object, but it's the path apparently. – David Small Aug 15 '16 at 17:28
  • 1
    Ah! 1. Output it to it's own file using the method above. 2. Note it as an 'external' resource in your webpack config. 3. `require` the _new_ file. – Quotidian Aug 15 '16 at 17:30
  • So the json is located in /pageJSON/config.json. In my externals, do I say 'config.json' : '/pageJSON/config.json' ? and then var jsonData = require('file?config.json!config.json'); ? – David Small Aug 15 '16 at 17:37
  • Why in a directory above the webpack output? I want the json in the webpack output so when it's deployed, I can edit the json file without having to repackage everything – David Small Aug 15 '16 at 17:54