npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

webpack-localize-assets-plugin

v1.5.4

Published

Localize your Webpack bundle with multiple locales

Downloads

5,327

Readme

webpack-localize-assets-plugin

Localize your Webpack bundle with multiple locales.

Features

  • Create bundles with localization baked in
  • Suports single & multiple locales
  • Blazing fast!

How does it compare to i18n-webpack-plugin? Answered in the FAQ.

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

🚀 Install

npm i -D webpack-localize-assets-plugin

🚦 Quick setup

  • Import webpack-localize-assets-plugin.
  • Include [locale] in output.filename to indicate where the locale name should go in the output file.
  • Register webpack-localize-assets-plugin with locales passed in.

In webpack.config.js:

+ const LocalizeAssetsPlugin = require('webpack-localize-assets-plugin')

  const locales = {
      en: { ... },
      es: { ... },
      ja: { ... },
      ...
  }

  module.exports = {
      ...,

      output: {
+         filename: '[name].[locale].js',
          ...
      },

      plugins: [
          ...,
+         new LocalizeAssetsPlugin({
+             locales
+         })
      ]
  }

⚙️ Options

locales

Required

Type:

type Locales = {
    [locale: string]: string | {
        [stringKey: string]: string
    }
}

An object containing all the localization strings.

The key should be the locale name, and the value can either be the path to the locale JSON file or an object mapping the string key to the localized string.

Using a JSON path has the advantage of automatically detecting changes across compilations, which is useful in development.

Example:

new LocalizeAssetsPlugin({
    locales: {
        en: './locales/en.json',
        es: './locales/es.json'
        // ...
    }
    // ...
})

Or:

new LocalizeAssetsPlugin({
    locales: {
        en: {
            helloWorld: 'Hello World!',
            goodbyeWorld: 'Goodbye World!'
            // ...
        },
        es: {
            helloWorld: '¡Hola Mundo!',
            goodbyeWorld: '¡Adiós Mundo!'
            // ...
        }
        // ...
    }
    // ...
})

functionName

Type: string

Default: __

The function name to use to detect localization string keys.

const message = __('helloWorld') // => 'Hello world!'

throwOnMissing

Type: boolean

Default: false

Throw an error if a string key is not found in a locale object.

sourceMapForLocales

Type: string[]

An array of locales that source-maps should be emitted for. Source-maps are enabled via devtool.

warnOnUnusedString

Type: boolean

Default: false

Enable to see warnings when unused string keys are found.

localizeCompiler

Type:

type LocalizeCompiler = {
    // localizer function name (eg. __)
    [functionName: string]: (
        this: LocalizeCompilerContext,
        localizerArguments: string[],
        localeName: string,
    ) => string
}

Default:

const localizeCompiler = {
    __(localizerArguments) {
        const [key] = localizerArguments
        const keyResolved = this.resolveKey()
        return keyResolved ? JSON.stringify(keyResolved) : key
    }
}

An object of functions to generate a JS string to replace the __() call with. The object key is the localize function name, and its function gets called for each localize function call (eg. __(...)) for each locale. This allows you to have multiple localization functions, with separate compilation logic for each of them.

Note, you cannot use both functionName and localizeCompiler. Simply set the function name as a key in the localizeCompiler object instead.

localizerArguments

An array of strings containing JavaScript expressions. The expressions are stringified arguments of the original call. So localizerArguments[0] will be a JavaScript expression containing the translation key.

localeName

The name of the current locale

this context

| Name | Type | Description | | - | - | - | | resolveKey | (key?: string) => string | A function to get the localized data given a key. Defaults to the key passed in. | | emitWarning | (message: string) => void | Call this function to emit a warning into the Webpack build. | | emitError | (message: string) => void | Call this function to emit an error into the Webpack build. | | callNode | CallExpression | AST node representing the original call to the localization function (eg. __()). |

localizeCompiler must return a string containing a JavaScript expression. The expression will be injected into the bundle in the place of the original __() call. The expression should represent the localized string.

You can use localizeCompiler to do inject more localization logic (eg. pluralization).

💁‍♀️ FAQ

How does this work and how is it so fast?

This plugin has two modes: Single-locale and Multi-locale.

In Single-locale mode, it works just like i18n-webpack-plugin. It replaces the localization calls with localized strings during Webpack's module parsing stage. Since there is only one locale, localization only needs to be done once at the earliest possible stage.

In Multi-locale mode, it inserts placeholders instead of the localized strings at the module parsing stage. After minification, all assets are duplicated for each locale and the placeholders are replaced with the localized strings via find-and-replace.

The speed gains come from:

  • Applying localization to minified assets. By doing so, we can avoid re-minifying the assets for each locale.
  • Using find-and-replace to localize. Find-and-replace is literally just looking for a pattern in a string and replacing it, so there is no AST parsing costs incurred for each locale.

How does this compare to i18n-webpack-plugin?

First of all, thank you to i18n-webpack-plugin for the original idea and implementation and serving the community.

webpack-localize-assets-plugin vs i18n-webpack-plugin:

  • Is actively maintained webpack-localize-assets-plugin is actively maintained. i18n-webpack-plugin is no longer developed/maintained and has been archived with no official alternative.
  • Has Wepback 5 support webpack-localize-assets-plugin supports Webpack 4 and 5. i18n-webpack-plugin only supports up to Webpack 4
  • Is optimized for multiple locales webpack-localize-assets-plugin is designed to support multiple locales efficiently (and it's blazing fast!). i18n-webpack-plugin only supports one locale so building with multiple locales requires complete re-builds for each one.

How does this approach compare to run-time localization?

There are two approaches to localization:

  • Build-time localization Happens during building/compiling. Localized strings are baked into the assets basically by find-and-replace. This plugin is an example of build-time localization.
  • Run-time localization Happens when the application is running. An asset with localized strings is loaded and strings are referenced by unique key.

Here is a comparison: