How can I 'bundle' a json file into a SharePoint Framework webpart?
-
11-10-2020 - |
Pergunta
I have a large block of JSON
I need to be available in my webpart, a 'canned' search result used when in the workbench and not connected to SharePoint.
Ideally I would like to reference it as follows:
const queryText = 'example';
const data = require(`json!./${queryText}.json`);
How do I get it packaged into the web part using webpack
?
Solução
So maybe I'm not quite reading the question correctly, but here is all I did.
- Put a sample.json file in the src/webpart directory
- Put
var sample:any = require('sample');
In my code, and that populates the sample variable with the json object.
Now, in order to get this to work where you specify the name with a variable, you need to do something a little bit different.
- Create a folder in the src/webpart directory. Let's call it JSON
- Stick all your json files in there
- Load them via
var simple:any = require('json/'+ queryText);
Webpack tries to be smart and bundle all the files it needs, but when it sees a variable rather than a literal, it doesn't really know what to bundle, so it basically bundles a bunch of stuff that it shouldn't, including stuff that isn't valid js, and your bundle is hosed. By putting it into a folder, it scopes down the things that it adds to the bundle, and everything is good.