A webpack loader that enables importing JSON files as JavaScript modules
npx @tessl/cli install tessl/npm-json-loader@0.5.0JSON Loader is a webpack loader that enables importing JSON files as JavaScript modules. It processes JSON content and returns it as a CommonJS module, handling special Unicode characters that could cause issues in JavaScript strings.
npm install --save-dev json-loaderJSON Loader is a webpack loader, not a direct module import. It's used through webpack configuration or inline loader syntax.
JSON Loader operates as a webpack loader in the webpack build pipeline:
Webpack 2.x+ (Modern):
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.json$/,
use: 'json-loader'
}
]
}
}Webpack 1.x (Legacy):
// webpack.config.js
module.exports = {
module: {
loaders: [
{
test: /\.json$/,
loader: 'json-loader'
}
]
}
}Then import JSON files directly:
const data = require('./file.json');
// or with ES6 imports
import data from './file.json';const json = require('json-loader!./file.json');Transforms JSON files into JavaScript modules that can be imported and used in webpack bundles.
/**
* JSON Loader function - processes JSON content and returns CommonJS module
* @param {string|*} source - The content of the JSON file being processed
* @returns {string} JavaScript module code that exports the JSON data
* @context webpack loader context (this.cacheable available if supported)
*/
module.exports = function (source) {
// Enables caching if supported by webpack
if (this.cacheable) this.cacheable();
// Parse JSON if source is string, otherwise use as-is
var value = typeof source === "string" ? JSON.parse(source) : source;
// Stringify and escape problematic Unicode characters
value = JSON.stringify(value)
.replace(/\u2028/g, '\\u2028') // Line separator
.replace(/\u2029/g, '\\u2029'); // Paragraph separator
// Return as CommonJS module
return `module.exports = ${value}`;
};The loader specifically handles two Unicode characters that can break JavaScript:
These characters are escaped to \\u2028 and \\u2029 respectively to prevent JavaScript parsing issues.
The loader calls this.cacheable() when available to enable webpack's caching mechanism, improving build performance for unchanged JSON files.
The loader accepts both:
JSON.parse().json files