I am trying to use the json2csv
javascript package in my Salesforce Web Component, but I get the error: can't find variable 'require'
.
I've uploaded the json2csv package as a static resource and am loading it via:
import JSON2CSV from '@salesforce/resourceUrl/JSON2CSV';
export default class MyComponent extends LightningElement {
/**
* Variables
*/
json2csvInitialized = false;
renderedCallback() {
if (this.json2csvInitialized) {
return;
}
this.json2csvInitialized = true;
Promise.all([
loadScript(this, JSON2CSV)
])
.then(() => {
var csvString = this.testJson2Csv(json);
console.log(csvString);
})
}
testJson2Csv() {
const Json2csvParser = require('json2csv').Parser;
const fields = ['carModel', 'price', 'items.name', 'items.color', 'items.items.position', 'items.items.color'];
const myCars = [
{
"carModel": "BMW",
"price": 15000,
"items": [
{
"name": "airbag",
"color": "white"
}, {
"name": "dashboard",
"color": "black"
}
]
}, {
"carModel": "Porsche",
"price": 30000,
"items": [
{
"name": "airbag",
"items": [
{
"position": "left",
"color": "white"
}, {
"position": "right",
"color": "gray"
}
]
}, {
"name": "dashboard",
"items": [
{
"position": "left",
"color": "gray"
}, {
"position": "right",
"color": "black"
}
]
}
]
}
];
const json2csvParser = new Json2csvParser({ fields, unwind: ['items', 'items.items'], unwindBlank: true });
const csv = json2csvParser.parse(myCars);
return csv;
}
}
What am I missing? How else am I suppose to use the parser?
Best Answer
Turns out you just need to replace
with