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

html-webpack-inline-i18n-plugin

v1.0.0

Published

HTMLWebpackPlugin's plugin for inlining i18n files from mini-i18n-extract-plugin

Downloads

3

Readme

html-webpack-inline-i18n-plugin

Latest Version Documentation contributions welcome License: MIT Package Size

Build Status Dependencies Known Vulnerabilities codecov Total alerts Language grade: JavaScript Maintainability


html-webpack-plugin plugin for inlining i18n assets, like those from mini-i18n-extract-plugin.

🏠 Homepage | 🗃 Repository | 📦 NPM | 📚 Documentation | 🐛 Issue Tracker

🪑 Table of Content

🧰 Features

Automatically inline information on all available translation files.

  • Indexed by locales.
  • Fetch the files when you need them.
  • Included assets, locale detection, and the inserted HTML tag and its position can all be overriden.

👶 Install

npm install -D html-webpack-inline-i18n-plugin

🚀 Usage

The plugin looks for translation (i18n) files among the assets emitted by Webpack, detects which locale the files relate to, and inserts the information to the HTML file created by html-webpack-plugin:

<!-- ./dist/index.html -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Webpack App</title>
  </head>
  <body>
    <!-- Following div is inserted by the plugin -->
    <div
      id="i18n"
      data-de="main.de.i18n.json"
      data-en="main.en.i18n.json"
    ></div>
    <script src="main.js"></script>
  </body>
</html>

The locales files can then be accessed on the webpage to fetch individual locales files when needed:

const localesData = window.document.querySelect('#i18n').dataset;
// or window.document.getElementById('i18n').dataset;

console.log(localesData);
// {
//    de: "main.de.i18n.json",
//    en: "main.en.i18n.json"
// }

// Get available locales
Object.keys(localesData);

// Fetch the translations
const response = await fetch(localesData.de);
const deData = response.json();

console.log(deData);
// {
//    greeting: "Tschüß!"
// }

The keys are extracted from the asset names. If you have a single file with all translations, or the regex that parses the asset name fails to match a locale name, the asset is stored under the default key instead.

const localesData = window.document.querySelect('#i18n').dataset;
// or window.document.getElementById('i18n').dataset;

console.log(localesData);
// {
//    default: "main.i18n.json"
// }

// Fetch the translations
const response = await fetch(localesData.default);
const data = response.json();

console.log(data);
// {
//    en: {
//      greeting: "Hello!"
//    },
//    de: {
//      greeting: "Tschüß!"
//    }
// }

When using this package, it is recommended to wrap it in a service that manages the retrieval of the asset files and loading of the data onto a package that provides the i18n functionality, like vue-18n.

Webpack config

The plugin requires HtmlWebpackPlugin among the webpack plugins.

// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackInlineI18nPlugin = require('html-webpack-inline-i18n-plugin')
  .default;
// or import HtmlWebpackInlineI18nPlugin from 'html-webpack-inline-i18n-plugin';

const htmlWebpackPlugin = new HtmlWebpackPlugin();
const inlineI18nPlugin = new HtmlWebpackInlineI18nPlugin();

module.exports = {
  ...
  plugins: [
    htmlWebpackPlugin, // creates index.html
    inlineI18nPlugin // inserts info on i18n files to index.html
  ],
};

Webpack config with MiniI18nExtractPlugin

By default, the plugin works with the default format of assets exported by MiniI18nExtractPlugin.

// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniI18nExtractPlugin = require('mini-i18n-extract-plugin').default;
// or import MiniI18nExtractPlugin from 'mini-i18n-extract-plugin';
const HtmlWebpackInlineI18nPlugin = require('html-webpack-inline-i18n-plugin')
  .default;
// or import HtmlWebpackInlineI18nPlugin from 'html-webpack-inline-i18n-plugin';

const i18nExtractPlugin = new MiniI18nExtractPlugin();
const htmlWebpackPlugin = new HtmlWebpackPlugin();
const inlineI18nPlugin = new HtmlWebpackInlineI18nPlugin();

module.exports = {
  ...
  module: {
    rules: [
      {
        test: /\.i18n\.json$/i,
        use: [i18nExtractPlugin.asLoader],
      },
    ],
  },
  plugins: [
    i18nExtractPlugin, // extracts i18n files
    htmlWebpackPlugin, // creates index.html
    inlineI18nPlugin // inserts info on i18n files to index.html
  ],
};

Typing

This project is written in TypeScript and the typings are included in the distribution. Available types can be imported as:

import { types } from 'html-webpack-inline-i18n-plugin';

Debugging

This project uses debug. To show debug logs, activate debug for html-webpack-inline-i18n-plugin.

CLI example:

DEBUG=html-webpack-inline-i18n-plugin node path/to/my/html-webpack-inline-i18n-plugin-project

🤖 API

TypeDoc documentation can be found here.

Options

Options are passed to the plugin on instantiation.

const MiniI18nExtractPlugin = require('mini-i18n-extract-plugin');

const i18nExtractPlugin = new MiniI18nExtractPlugin({
  // pass them configs here
  include: /\.i18n/iu,
  ...
});

The plugin accepts the following options:

include

  • Type: RegExp | string | (PatternContext) => (RegExp | string)

  • RegExp pattern that specifies which assets should be recognized and made available as locales files.

    Can be either a RegExp, string regex, or a function that returns one of the former.

  • Defaults to /\.i18n/iu.

exclude

  • Type: RegExp | string | (PatternContext) => (RegExp | string)

  • RegExp pattern that specifies which assets should be excluded from the assets matched by the include option.

    Can be either a RegExp, string regex, or a function that returns one of the former.

  • No default.

extractLocale

  • Type: RegExp | string | (PatternContext) => (RegExp | string)

  • RegExp pattern that specifies which part of the asset name is the locale.

    The regex must have a match group. The locale has to be either the first match group, or a match group labeled locale.

    Can be either a RegExp, string regex, or a function that returns one of the former.

  • Defaults to function defined at src/lib/extract-locale.

modifyTag

  • Type: (ModifyTagContext) => HtmlTagObject

  • Function that is given (among other) the object representation of the to-be-generated HTML tag with i18n data, and returns the updated object.

    This function should be used if you need to modify either the properties, the tag type, or other aspects of the HTML tag.

  • No default.

position

  • Type: 'before' | 'after' | (PositionContext) => HtmlTagObject[]

  • Specify the position where the i18n tag should be inserted into the HTML body.

  • Can be one of:

    • 'before' - insert the i18n tag before other HTML tags in body
    • 'after' - insert the i18n tag after other HTML tags in body
    • Function - Function that is given (among other) the list of tags to be inserted into the HTML body, and returns the update list of tags. The order of the returned list decides the order in which the tags will be rendered in the HTML body.
  • Defaults to 'before'.

Contexts

Options that can be functions are passed the data (context) that's available at their invokation.

Here is the list of used contexts:

ModifyTagContext

The context object passed to modifyTag function.

| Property | Description | Type | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | i18nTag | HtmlTagObject for the to-be-generated tag containing i18n information. | HtmlTagObject | | assets | Object with assets data, as defined by HtmlWebpackPlugin | object | | outputName | HTML file output name, as defined by HtmlWebpackPlugin | string | | plugin | HtmlWebpackPlugin instance, as defined by HtmlWebpackPlugin | HtmlWebpackPlugin |

PatternContext

The context object passed to functions that return RegExp patterns for filtering assets and extracting locale info from asset filenames.

| Property | Description | Type | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------- | | filename | Name of the asset at hand. | string | | chunk | Webpack's Chunk that the asset at hand relates to. | Chunk | | assets | Object with assets data, as defined by HtmlWebpackPlugin | object | | outputName | HTML file output name, as defined by HtmlWebpackPlugin | string | | plugin | HtmlWebpackPlugin instance, as defined by HtmlWebpackPlugin | HtmlWebpackPlugin |

PositionContext

The context object passed to the position option if it is a function.

| Property | Description | Type | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | i18nTag | HtmlTagObject for the to-be-generated tag containing i18n information. | HtmlTagObject | | headTags | List of HtmlTagObjects that will be inserted as HTML tags to head, as defined by HtmlWebpackPlugin | HtmlTagObject[] | | bodyTags | List of HtmlTagObjects that will be inserted as HTML tags to body, as defined by HtmlWebpackPlugin | HtmlTagObject[] | | outputName | HTML file output name, as defined by HtmlWebpackPlugin | string | | plugin | HtmlWebpackPlugin instance, as defined by HtmlWebpackPlugin | HtmlWebpackPlugin |

⏳ Changelog

This projects follows semantic versioning. The changelog can be found here.

🛠 Developing

If you want to contribute to the project or have forked it, this guide will get you up and going.

🏗 Roadmap

There is no explicit roadmap for this project. However, if you have ideas how it could be improved, please be sure to share it with us by opening an issue.

🤝 Contributing

Contributions, issues and feature requests are welcome! Thank you ❤️

Feel free to dive in! See current issues, open an issue, or submit PRs.

How to report bugs, feature requests, and how to contribute and what conventions we use is all described in the contributing guide.

When contributing we follow the Contributor Covenant. See our Code of Conduct.

🧙 Contributors

Contributions of any kind welcome. Thanks goes to these wonderful people ❤️

Recent and Top Contributors

Hall of Fame Contributor 1 Hall of Fame Contributor 2 Hall of Fame Contributor 3 Hall of Fame Contributor 4 Hall of Fame Contributor 5 Hall of Fame Contributor 6 Hall of Fame Contributor 7 Hall of Fame Contributor 8

Generated using Hall of Fame.

All Contributors

Contribution type emoji legend

No additional contributors. Be the first one!

This project follows the all-contributors specification.

⭐ Show your support

Give a ⭐️if this project helped you!

🐙 Community

🔗 Related Projects

👨‍🔧 Maintainers

👤 Juro Oravec

📝 License

Copyright © 2020 Juro Oravec.

This project is MIT licensed.