In ECMAScript 6 (ES6), importing a JSON file directly using the import statement is not natively supported. However, there are several methods to achieve this functionality:
1. Using fetch in Browser Environments:
In browser environments, you can use the fetch API to load and parse a local JSON file.
Example:
fetch('./data.json')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
2. Using import with Assertions (Experimental in Node.js):
As of Node.js v17.1.0, importing JSON files using import assertions is an experimental feature.
Example:
import data from './data.json' assert { type: 'json' };
console.log(data);