Search code examples
djangowebpackdjango-i18nxgettext

Webpack TypeScript and xgettext translations


I have a Django app and am using Django's i18n module to help translating my strings. For translating JavaScript, I run

python manage.py makemessages -d djangojs

which adds all marked strings to a .po file. This works quite well for all my boring .js files in my static folder. However, we are starting to use webpack to pack some typescript (.tsx files) into a bundle.js file. This file is copied to the static folder after building, so I expected Djangos makemessages to pick up the strings from it as well. However, it seems that the strings are not parsed correctly, because most of the code in bundle.js is simply strings wrapped in eval().

I believe this means that I need webpack to - in addition to the bundle.js file - create a .js file for each .tsx file without all of the eval() nonsense, so that django's makemessages can parse it properly. I have no idea how to do this, however. My current config looks like this

var path = require("path");
var WebpackShellPlugin = require('webpack-shell-plugin');

var config = {
    entry: ["./src/App.tsx"],

    output: {
        path: path.resolve(__dirname, "build"),
        filename: "bundle.js"
    },

    devtool: 'source-map',

    resolve: {
        extensions: [".ts", ".tsx", ".js"]
    },

    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: "ts-loader",
                exclude: /node_modules/
            },
            {
            test: /\.scss$/,
                use: [{
                    loader: "style-loader" // creates style nodes from JS strings
                }, {
                    loader: "css-loader" // translates CSS into CommonJS
                }, {
                    loader: "sass-loader" // compiles Sass to CSS
                }]
            },
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader'
            }
        ]
    },

    plugins: [
        new WebpackShellPlugin({
            onBuildEnd:['./cp_to_static.sh'],
            dev: false  // Needed to trigger on npm run watch
        })
    ]
};

module.exports = config;
  • So how can I make webpack spit out these files?
  • Is this the right thing to do, or is there a way to make Django parse bundle.js properly?

Solution

  • Turns out that all of the eval nonsense was generated by webpacks "watch" function. When simply running webpack for building the script, it works as expected