Skip to content

Commit

Permalink
Add namespace to configuration, command option and api. This will all…
Browse files Browse the repository at this point in the history
…ow user to specify the namespace of compiled js file: ex: export default or module.export or window.translations
  • Loading branch information
An Nguyen committed Aug 28, 2018
1 parent 0144276 commit d0e63b8
Show file tree
Hide file tree
Showing 10 changed files with 140 additions and 25 deletions.
10 changes: 10 additions & 0 deletions .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,16 @@
"code",
"doc"
]
},
{
"login": "dephiros",
"name": "An Nguyen",
"avatar_url": "https://avatars1.githubusercontent.com/u/2289753?v=4",
"profile": "https://github.com/dephiros",
"contributions": [
"code",
"doc"
]
}
],
"repoType": "github"
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ on production build. You can do the same in your project:

2. Packages are inside `build/packages` directory. First, run `yalc publish` in each
of them and then run `yalc link <package>` for each `@lingui/` dependency in your
project. Now you project uses your local version of `jsLingui`.
project. Now your project uses your local version of `jsLingui`.

3. After you make some changes, you need to run `yarn release:build` only.

Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ I18n libraries for JavaScript focused on high quality developer experience
[![AppVeyor][Badge-AppVeyor]][AppVeyor]
[![Code Coverage][Badge-Coverage]][Coverage]
[![PRs Welcome][Badge-PRWelcome]][PRWelcome]
[![All Contributors](https://img.shields.io/badge/all_contributors-14-orange.svg?style=flat-square)](#contributors)
[![All Contributors](https://img.shields.io/badge/all_contributors-15-orange.svg?style=flat-square)](#contributors)
[![Watch on GitHub][Badge-Watch]][Watch]
[![Star on GitHub][Badge-Stars]][Star]
[![Tweet][Badge-Twitter]][Twitter]
Expand Down Expand Up @@ -83,6 +83,7 @@ Big thanks goes to these people ([emoji key][emojis]):
| [<img src="https://avatars1.githubusercontent.com/u/827862?v=3" width="100px;"/><br /><sub><b>Tomáš Ehrlich</b></sub>](http://www.tomasehrlich.cz)<br />[💻](https://github.com/lingui/js-lingui/commits?author=tricoder42 "Code") [📖](https://github.com/lingui/js-lingui/commits?author=tricoder42 "Documentation") [💡](#example-tricoder42 "Examples") [✅](#tutorial-tricoder42 "Tutorials") | [<img src="https://avatars1.githubusercontent.com/u/3697116?v=3" width="100px;"/><br /><sub><b>Josef Hornych</b></sub>](https://github.com/Peping)<br />[📖](https://github.com/lingui/js-lingui/commits?author=Peping "Documentation") [🐛](https://github.com/lingui/js-lingui/issues?q=author%3APeping "Bug reports") | [<img src="https://avatars2.githubusercontent.com/u/307006?v=3" width="100px;"/><br /><sub><b>Christian Kaps</b></sub>](https://www.silhouette.rocks)<br />[🐛](https://github.com/lingui/js-lingui/issues?q=author%3Aakkie "Bug reports") | [<img src="https://avatars0.githubusercontent.com/u/2085291?v=3" width="100px;"/><br /><sub><b>brunesto</b></sub>](https://github.com/brunesto)<br />[💻](https://github.com/lingui/js-lingui/commits?author=brunesto "Code") [🐛](https://github.com/lingui/js-lingui/issues?q=author%3Abrunesto "Bug reports") | [<img src="https://avatars0.githubusercontent.com/u/614768?v=3" width="100px;"/><br /><sub><b>David Furlong</b></sub>](https://davidfurlong.github.io/)<br />[💬](#question-davidfurlong "Answering Questions") | [<img src="https://avatars2.githubusercontent.com/u/1416801?v=4" width="100px;"/><br /><sub><b>Thibaut</b></sub>](http://thibaut.re)<br />[🐛](https://github.com/lingui/js-lingui/issues?q=author%3AthibautRe "Bug reports") [📖](https://github.com/lingui/js-lingui/commits?author=thibautRe "Documentation") | [<img src="https://avatars1.githubusercontent.com/u/2965120?v=4" width="100px;"/><br /><sub><b>Sebastian Sobociński</b></sub>](https://github.com/hiddenboox)<br />[💻](https://github.com/lingui/js-lingui/commits?author=hiddenboox "Code") |
| :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| [<img src="https://avatars2.githubusercontent.com/u/296106?v=4" width="100px;"/><br /><sub><b>Matt Labrum</b></sub>](https://github.com/mlabrum)<br />[📖](https://github.com/lingui/js-lingui/commits?author=mlabrum "Documentation") | [<img src="https://avatars1.githubusercontent.com/u/1098399?v=4" width="100px;"/><br /><sub><b>Vincent Ricard</b></sub>](https://github.com/ghostd)<br />[📖](https://github.com/lingui/js-lingui/commits?author=ghostd "Documentation") | [<img src="https://avatars2.githubusercontent.com/u/2378900?v=4" width="100px;"/><br /><sub><b>Adam Gruber</b></sub>](https://github.com/adamgruber)<br />[💻](https://github.com/lingui/js-lingui/commits?author=adamgruber "Code") | [<img src="https://avatars1.githubusercontent.com/u/1268629?v=4" width="100px;"/><br /><sub><b>Spencer Mefford</b></sub>](https://github.com/spencermefford)<br />[💻](https://github.com/lingui/js-lingui/commits?author=spencermefford "Code") | [<img src="https://avatars2.githubusercontent.com/u/1448788?v=4" width="100px;"/><br /><sub><b>Jeow Li Huan</b></sub>](https://github.com/huan086)<br />[💻](https://github.com/lingui/js-lingui/commits?author=huan086 "Code") | [<img src="https://avatars1.githubusercontent.com/u/1566403?v=4" width="100px;"/><br /><sub><b>Vojtech Novak</b></sub>](https://github.com/vonovak)<br />[📖](https://github.com/lingui/js-lingui/commits?author=vonovak "Documentation") | [<img src="https://avatars0.githubusercontent.com/u/1096340?v=4" width="100px;"/><br /><sub><b>Daniel K.</b></sub>](https://gitconnected.com/fredyc)<br />[💻](https://github.com/lingui/js-lingui/commits?author=FredyC "Code") [📖](https://github.com/lingui/js-lingui/commits?author=FredyC "Documentation") |
| [<img src="https://avatars1.githubusercontent.com/u/2289753?v=4" width="100px;"/><br /><sub><b>An Nguyen</b></sub>](https://github.com/dephiros)<br />[💻](https://github.com/lingui/js-lingui/commits?author=dephiros "Code") [📖](https://github.com/lingui/js-lingui/commits?author=dephiros "Documentation") |
<!-- ALL-CONTRIBUTORS-LIST:END -->

This project follows the [all-contributors][all-contributors] specification.
Expand Down
5 changes: 4 additions & 1 deletion docs/ref/cli.rst
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ Prints additional information.
``compile``
-----------

.. lingui-cli:: compile [--strict] [--format <format>] [--verbose]
.. lingui-cli:: compile [--strict] [--format <format>] [--verbose] [--namespace <namespace>]

This command compiles message catalogs in :conf:`localeDir` and outputs
minified Javascript files. Each message is replaced with a function
Expand All @@ -150,5 +150,8 @@ Format of message catalogs (see :conf:`format` option).

Prints additional information.

.. lingui-cli-option:: --namespace

Specify namespace for compiled message catalogs (see :conf:`namespace` option).

.. _npx: https://github.com/zkat/npx
28 changes: 28 additions & 0 deletions docs/ref/conf.rst
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,31 @@ Specify extra babel options used to parse source files when messages are being e
"plugins": ["@babel/plugin-syntax-dynamic-import"]
}
}
namespace
---------

Default: ``cjs``

Specify namespace for compiling messages.

cjs
^^^

.. code-block:: js
/* eslint-disable */module.exports={languageData:{"..."}, "...": "..."}
es
^^

.. code-block:: js
/* eslint-disable */export default{languageData:{"..."}, "...": "..."}
(window|global).(.*)
^^^^^^^^^^^^^^^^^^^^

.. code-block:: js
/* eslint-disable */window.test={languageData:{"..."}, "...": "..."}
10 changes: 10 additions & 0 deletions packages/cli/src/api/__snapshots__/compile.test.js.snap
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`compile should report failed message on error 1`] = `Can't parse message. Please check correct syntax: "{value, plural, one {Book} other {Books"`;
exports[`createCompiledCatalog namespace should compile with cjs by default 1`] = `"/* eslint-disable */module.exports={languageData:{\\"plurals\\":function(n,ord){if(ord)return n==1?\\"one\\":\\"other\\";return n>=0&&n<2?\\"one\\":\\"other\\"}},messages:{}};"`;
exports[`createCompiledCatalog namespace should compile with es 1`] = `"/* eslint-disable */export default{languageData:{\\"plurals\\":function(n,ord){if(ord)return n==1?\\"one\\":\\"other\\";return n>=0&&n<2?\\"one\\":\\"other\\"}},messages:{}};"`;
exports[`createCompiledCatalog namespace should compile with global 1`] = `"/* eslint-disable */global.test={languageData:{\\"plurals\\":function(n,ord){if(ord)return n==1?\\"one\\":\\"other\\";return n>=0&&n<2?\\"one\\":\\"other\\"}},messages:{}};"`;
exports[`createCompiledCatalog namespace should compile with window 1`] = `"/* eslint-disable */window.test={languageData:{\\"plurals\\":function(n,ord){if(ord)return n==1?\\"one\\":\\"other\\";return n>=0&&n<2?\\"one\\":\\"other\\"}},messages:{}};"`;
exports[`createCompiledCatalog namespace should error with invalid value 1`] = `"Invalid namespace param: \\"global\\""`;
60 changes: 42 additions & 18 deletions packages/cli/src/api/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,37 @@ function processTokens(tokens, arg) {
)
}

function buildExportStatement(expression, namespace: string = "cjs") {
namespace = namespace.trim()
if (namespace === "es") {
return t.ExportDefaultDeclaration(expression)
} else {
let exportExpression = null
const matches = namespace.match(/^(window|global)\.([^.\s]+)$/)
if (namespace === "cjs") {
exportExpression = t.memberExpression(
t.identifier("module"),
t.identifier("exports")
)
} else if (matches) {
exportExpression = t.memberExpression(
t.identifier(matches[1]),
t.identifier(matches[2])
)
} else {
throw new Error(`Invalid namespace param: "${namespace}"`)
}
return t.expressionStatement(
t.assignmentExpression("=", exportExpression, expression)
)
}
}

export function createCompiledCatalog(
locale: string,
messages: CatalogType,
strict: boolean = false
strict: boolean = false,
namespace: string = "cjs"
) {
const [language] = locale.split(/[_-]/)
const pluralRules = plurals[language]
Expand All @@ -116,23 +143,20 @@ export function createCompiledCatalog(
)
]

const ast = t.expressionStatement(
t.assignmentExpression(
"=",
t.memberExpression(t.identifier("module"), t.identifier("exports")),
t.objectExpression([
// language data
t.objectProperty(
t.identifier("languageData"),
t.objectExpression(languageData)
),
// messages
t.objectProperty(
t.identifier("messages"),
t.objectExpression(compiledMessages)
)
])
)
const ast = buildExportStatement(
t.objectExpression([
// language data
t.objectProperty(
t.identifier("languageData"),
t.objectExpression(languageData)
),
// messages
t.objectProperty(
t.identifier("messages"),
t.objectExpression(compiledMessages)
)
]),
namespace
)

return (
Expand Down
30 changes: 29 additions & 1 deletion packages/cli/src/api/compile.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import generate from "babel-generator"
import { compile } from "./compile"
import { compile, createCompiledCatalog } from "./compile"

describe("compile", function() {
const getSource = message =>
Expand Down Expand Up @@ -74,3 +74,31 @@ describe("compile", function() {
).toThrowErrorMatchingSnapshot()
})
})

describe("createCompiledCatalog", function() {
describe("namespace", function() {
const getCompiledCatalog = (...args) =>
createCompiledCatalog("fr", {}, ...args)
it("should compile with cjs by default", function() {
expect(getCompiledCatalog()).toMatchSnapshot()
})

it("should compile with es", function() {
expect(getCompiledCatalog(false, "es")).toMatchSnapshot()
})

it("should compile with window", function() {
expect(getCompiledCatalog(false, "window.test")).toMatchSnapshot()
})

it("should compile with global", function() {
expect(getCompiledCatalog(false, "global.test")).toMatchSnapshot()
})

it("should error with invalid value", function() {
expect(() =>
getCompiledCatalog(false, "global")
).toThrowErrorMatchingSnapshot()
})
})
})
14 changes: 12 additions & 2 deletions packages/cli/src/lingui-compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,12 @@ function command(config, options) {
}
}

const compiledCatalog = createCompiledCatalog(locale, messages)
const compiledCatalog = createCompiledCatalog(
locale,
messages,
false,
options.namespace || config.namespace
)
const compiledPath = catalog.writeCompiled(locale, compiledCatalog)
if (options.typescript) {
const typescriptPath = compiledPath.replace(/\.js$/, "") + ".d.ts"
Expand All @@ -114,6 +119,10 @@ if (require.main === module) {
.option("--verbose", "Verbose output")
.option("--format <format>", "Format of message catalog")
.option("--typescript", "Create Typescript definition for compiled bundle")
.option(
"--namespace <namespace>",
"Specify namespace for compiled bundle. Ex: cjs(default) -> module.exports, window.test -> window.test"
)
.on("--help", function() {
console.log("\n Examples:\n")
console.log(
Expand Down Expand Up @@ -141,7 +150,8 @@ if (require.main === module) {
const results = command(config, {
verbose: program.verbose || false,
allowEmpty: !program.strict,
typescript: program.typescript || false
typescript: program.typescript || false,
namespace: program.namespace // we want this to be undefined if user does not specify so default can be used
})

if (!results || results.some(res => !res)) {
Expand Down
3 changes: 2 additions & 1 deletion packages/conf/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ export const defaultConfig = {
extractBabelOptions: {
plugins: [],
presets: []
}
},
namespace: "cjs"
}

const deprecatedConfig = {
Expand Down

0 comments on commit d0e63b8

Please sign in to comment.