Webpack plugin to tree-shake and minify JSON modules

Overview

webpack-json-access-optimizer

Optimize JSON modules that are referenced via accessor function. For example, i18n locale JSONs.

Features

  • Tree shaking Remove unused JSON entries
  • Optimize JSON structure Minify JSON by converting to an array
  • Developer friendly Warn on invalid JSON keys and invalid accessor usage
  • Persistent caching support Designed to support Webpack 5 disk cache

Support this project by ⭐️ starring and sharing it. Follow me to see what other cool projects I'm working on! ❤️

Example

Before

Given a "global accessor function" $t that retruns values from locale.json:

index.js

console.log($t('helloWorld')) // logs "Hello world!"

locale.json

{
    "helloWorld": "Hello world!",
    "unusedString": "I'm never accessed"
}

After optimization

index.js

console.log($t(0)) // logs "Hello world!"

locale.json

["Hello world!"]

Note:

  • The JSON is minified into an array, and the accessor now uses the array indices to access values
  • Unused entries are removed from the JSON

🚀 Install

npm i -D webpack-json-access-optimizer

🚦 Quick setup

Assuming you have some sort of "global accessor function" that takes a JSON key and returns the JSON value (eg. via ProvidePlugin):

  1. Import the JsonAccessOptimizer plugin from webpack-json-access-optimizer.
  2. Register the plugin with the "global accessor function" name
  3. Add the webpack-json-access-optimizer loader to the JSON files. Note, all JSON files must have identical keys.

In webpack.config.js:

+ const { JsonAccessOptimizer } = require('webpack-json-access-optimizer')

  module.exports = {
    ...,

    module: {
      rules: [
        ...,
+       {
+         test: /locale\.json$/, // match JSON files to optimize
+         loader: 'webpack-json-access-optimizer'
+       },
      ]
    },

    plugins: [
      ...,
+     new JsonAccessOptimizer({
+       accessorFunctionName: '$t', // localization function name
+     })
    ]
  }

JS loader

If the JSON needs to be transformed to JavaScript via another loader, you can chain them:

In webpack.config.js:

  module.exports = {
    ...,

    module: {
      rules: [
        ...,
        {
          test: /locale\.json$/, // match JSON files to optimize
          use: [
+           'some-other-json-transformer-loader', // any loader to transform JSON to JS
            'webpack-json-access-optimizer'
          ],
+         type: 'javascript/auto'
        },
      ]
    },
  }

⚙️ Plugin API

accessorFunctionName

Type: string

Required

The name of the "global accessor function" that takes a JSON key and returns the JSON value. This function is typically provided via another plugin like ProvidePlugin.

You might also like...

This a todo list project that uses webpack. In this project you will find features like adding tasks, deleting tasks, maintaining localstorage, marking tasks completed and clearing all completed tasks.

webpack-Todo list This a todo list project that uses webpack. In this project you will find features like adding tasks, deleting tasks, maintaining lo

Jun 15, 2022

React Starter Kit — isomorphic web app boilerplate (Node.js, Express, GraphQL, React.js, Babel, PostCSS, Webpack, Browsersync)

React Starter Kit — isomorphic web app boilerplate (Node.js, Express, GraphQL, React.js, Babel, PostCSS, Webpack, Browsersync)

React Starter Kit — "isomorphic" web app boilerplate React Starter Kit is an opinionated boilerplate for web development built on top of Node.js, Expr

Dec 30, 2022

React/Express/Webpack Boilerplate

React Boilerplate The following repo contains a very basic setup git clone https://github.com/asieke/React-Express-Boilerplate.git cd React-Express-Bo

Dec 30, 2022

Document Typescript React components with TSDoc and export Storybook-friendly JSON 🤖

Document Typescript React components with TSDoc and export Storybook-friendly JSON 🤖

✨ Document React components with @prop ✨ react-tsdoc 🤖 react-tsdoc is an tool to extract information from React Typescript component files with TSDoc

Oct 15, 2022

Extract the JSON payload from SHC QR codes (i.e Québec Covid Vaccination QR Codes)

Extract the JSON payload from SHC QR codes (i.e Québec Covid Vaccination QR Codes)

shc-extractor Extract the JSON payload from SHC QR Codes (i.e Québec COVID Vaccination QR Codes) Introduction Dans les prochains jours/semaines, les q

Dec 16, 2022

A React application for AddressBook to manage contacts on web. It will use JSON-server to create backend apis.

Available Scripts In the project directory, you can run: npm install To install all related packages npm start Runs the app in the development mode. O

Jan 10, 2022

Script to remove unnecessary properties from package.json on prepublish hook

clean-pkg-json Script to remove unnecessary properties from package.json on prepublish hook. Support this project by ⭐️ starring and sharing it. Follo

Oct 16, 2022

A markdown-it plugin and Nunjucks async filter to make working with Cloudinary in Eleventy easier.

Cloudinary Eleventy Helpers This is a collection of Eleventy Cloudinary helpers. It currently includes: A markdown-it plugin that converts local image

Feb 2, 2022

ESLint plugin for react-hook-form

eslint-plugin-react-hook-form react-hook-form is an awsome library which provide a neat solution for building forms. However, there are many rules for

Nov 22, 2022
Comments
  • fix: prevent duplicate warnings on static modules

    fix: prevent duplicate warnings on static modules

    Problem

    Static modules like dependencies are not regenerated on build, and therefore warnings on them can build up.

    Changes

    Check existing warnings for duplication before adding them.

    released 
    opened by privatenumber 1
  • Multi-json example?

    Multi-json example?

    Hi, I'm looking to build a multi-lingual app with a JSON each for every supported language (only a handful). So, in addition to requesting the key that I want, I also need to specify the locale that I care about.

    Instead of $t("helloWorld"), I need to be able to specify say $t("helloWorld", "en_US") or $t("helloWorld", "fr_FR").

    Alternatively, even something like $en("helloWorld") and $fr("helloWorld") could do as well.

    Can you describe what can I do to achieve this? The former allows me to have one accessorFunctionName, but it doesn't appear that I can add multiple arguments. The latter means I need to specify more than one accessorFunctionName.

    pr welcome 
    opened by vwong 2
  • Add this Demo to the README

    Add this Demo to the README

    Add this Demo Repository to the README.

    I mean, really, you should lol. I was setting this whole thing up, and it took me 2 days of intense debugging to get it to work properly.

    At first, I was pairing it up with Babel & JSON Loader, which wasn't working. Most people trying to set this up wouldn't have an idea how to make $t available in the global scope (I had no clue too, for almost two days, since your example doesn't explicitly mention how it is set up).

    Looks like now that I finally got it working, it would helpful for others to access a working demo quickly, without them having to scratch their heads on it lol.

    opened by kumarabhirup 0
Releases(v1.1.0)
Owner
hiroki osame
I'm on a mission to open source my solutions 🚀
hiroki osame
JSON Hero is an open-source, beautiful JSON explorer for the web that lets you browse, search and navigate your JSON files at speed. 🚀

JSON Hero makes reading and understand JSON files easy by giving you a clean and beautiful UI packed with extra features.

JSON Hero 7.2k Jan 9, 2023
A plugin that lets you override the Webpack modules public path in webpage runtime.

dynamic-public-path-plugin A plugin that lets you override the Webpack modules public path in webpage runtime. plugin : webpack-runtime-public-path-pl

dxh_vip 4 Jan 25, 2022
This is a simpler project than the full webpack source code, and you can understand the design ideas in webpack through it

my-webpack 这是一个简化版的webpack,旨在于理解webpack的设计原理以及webpack当中 loader和plugin的区别,运行方式。 运行步骤如下(方案一): 切换到my-webpack目录,运行npm install 切换到test目录,运行npm install 在tes

null 14 Sep 30, 2022
Webpack is an open-source JavaScript module bundler. This includes basic setup files to help me not redo all the setups for webpack when starting a new project.

Webpack Setup Webpack is an open-source JavaScript module bundler. It is made primarily for JavaScript, but it can transform front-end assets such as

Nemwel Boniface 14 Jun 23, 2022
.properties file parser, JSON converter and Webpack loader.

properties-file .properties file parser, JSON converter and Webpack loader. Installation ?? ⚠ in June 2022 we have released version 2 of this package

Avansai 6 Dec 15, 2022
Webpack plugin that helps importing .cdc files

cadence-webpack-plugin Webpack plugin that helps importing .cdc files and polyfills fcl dependencies This fixes the Buffer is not defined and Module n

AE Studio 8 Dec 8, 2022
A set of React components implementing Google's Material Design specification with the power of CSS Modules

React Toolbox is a set of React components that implement Google's Material Design specification. It's powered by CSS Modules and harmoniously integra

React Toolbox 8.7k Dec 30, 2022
Get an array of all React Spectrum modules, useful for integrating with Next.js

get-react-spectrum-modules This package exports a function that returns an array of all React Spectrum modules that it finds in the node_modules direc

Marc Abramowitz 1 Mar 8, 2022
A complete set up of the React application with Typescript, Webpack 5, Babel v7, SSR, Code Splitting and HMR.

Getting Started with react-final-boilerplate Clone the code npm install You are good to go with React Application. Open http://localhost:3000/ and you

null 24 Dec 22, 2022
Single Page Application with React, React Router, PostCSS, Webpack, Docker and Docker Compose.

spa-store Single Page Application with React, React Router, PostCSS, Webpack, Docker and Docker Compose. Contributing Feedback Roadmap Releases Check

Luis Falcon 2 Jul 4, 2022