Search code examples
javascriptwebpackinternationalizationlocal-storagelang

how can i get the lang html attribute in webpack configuration


    const lang = "the lang html attribute value";

    var languages = {
        "fr": require("./languages/fr.json"),
        "en": require("./languages/en.json")
    };

    var configuration = Object.keys(languages).map(function(language) {
        const loadedLang = (lang.indexOf("fr") > -1) ? "fr" : "en";
        return {
            name: loadedLang,
            entry: './assets/js/main.js',
            output: {
                filename: 'bundle.js',
                path: path.resolve(__dirname, 'assets/js/dist')
            },
            plugins: [
                new I18nPlugin(
                    languages[loadedLang]
                )
            ]
        }
    });

So I am trying to get the <html lang="en-US"> lang attribute and I know that I have no access to the DOM from the webpack config file.

My question is:

Does someone have an idea about how to do this or how to have access to the local storage from webpack?

PS: I tried a node-localstorage package but it doesn't do the job I want


Solution

  • An answer to your question would be to load the file with the fs api and then use an regex to extract your language:

    const fs = require('fs');
    const content = fs.readFileSync('PATH_TO_INDEX.HTML', options: { encoding: 'utf8' });
    const lang = content.match(/<html lang="(.*)"/)[1];
    

    But I would recommend to do it the "webpack" way:

    Create a separate folder for every language, that contains the index.html and the js file specific to each language language.

    For this, add the following:

    output: {
     path: path.resolve(__dirname, `assets/js/dist/${language}/`)
    },
    plugins: [
     new HtmlWebpackPlugin({
       template: 'PATH_TO_YOUR_TEMPLATE',
       lang: language,
       title: 'your page title',
     })
    ]
    

    Please don't forget to install the html-webpack-plugin and require it at the top of your config.

    And create a new file index.html with the following content:

    <!DOCTYPE html>
    <html lang="<%= htmlWebpackPlugin.options.lang %>">
      <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
        <title><%= htmlWebpackPlugin.options.title %></title>
      </head>
      <body>
      </body>
    </html>
    

    So now for every language a separate index.html with the right language and the right js file for that language is created in every language folder.

    So not the html file dictates the language set, but the webpack config.