Created
July 8, 2020 20:18
-
-
Save ScriptedAlchemy/4d3f8e63d16d9b9150e30e8083d91048 to your computer and use it in GitHub Desktop.
lingui loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Modified version of @lingui/loader. | |
// Current version does not read message catalogs correctly. | |
// https://github.com/lingui/js-lingui/blob/388464825440b7df3f20a549e425399f8a64c0b7/packages/loader/src/index.js | |
const path = require("path"); | |
const { getConfig } = require("@lingui/conf"); | |
const { createCompiledCatalog, configureCatalog } = require("@lingui/cli/api"); | |
const loaderUtils = require("loader-utils"); | |
// Check if JavascriptParser and JavascriptGenerator exists -> Webpack 4 | |
let JavascriptParser; | |
let JavascriptGenerator; | |
try { | |
JavascriptParser = require("webpack/lib/Parser"); | |
JavascriptGenerator = require("webpack/lib/JavascriptGenerator"); | |
} catch (error) { | |
if (error.code !== "MODULE_NOT_FOUND") { | |
throw e; | |
} | |
} | |
exports.default = function(source) { | |
const options = loaderUtils.getOptions(this) || {}; | |
// Webpack 4 uses json-loader automatically, which breaks this loader because it | |
// doesn't return JSON, but JS module. This is a temporary workaround before | |
// official API is added (https://github.com/webpack/webpack/issues/7057#issuecomment-381883220) | |
// See https://github.com/webpack/webpack/issues/7057 | |
if (JavascriptParser && JavascriptGenerator) { | |
this._module.type = "javascript/auto"; | |
this._module.parser = new JavascriptParser(); | |
this._module.generator = new JavascriptGenerator(); | |
} | |
const config = getConfig({ | |
configPath: options.config, | |
cwd: path.dirname(this.resourcePath) | |
}); | |
const catalog = configureCatalog(config); | |
const locale = catalog.getLocale(this.resourcePath); | |
const messages = JSON.parse(source); | |
// In production we don't want untranslated strings. It's better to use message | |
// keys as a last resort. | |
// In development, however, we want to catch missing strings with `missing` parameter | |
// of I18nProvider (React) or setupI18n (core) and therefore we need to get | |
// empty translations if missing. | |
const strict = process.env.NODE_ENV !== "production"; | |
return createCompiledCatalog( | |
locale, | |
messages, | |
strict, | |
config.compileNamespace, | |
config.pseudoLocale | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment