Skip to content

Commit

Permalink
Merge branch 'release/0.12.0' into npm
Browse files Browse the repository at this point in the history
  • Loading branch information
mashpie committed Aug 16, 2020
2 parents 9c69722 + ee1512e commit 9cffae2
Show file tree
Hide file tree
Showing 44 changed files with 422 additions and 169 deletions.
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
10
12
6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
test.examples:
mocha --exit examples/express4-cookie/test.js
mocha --exit examples/express4-setLocale/test.js
mocha --exit examples/node-http/test.js
mocha --exit examples/node-http-autoreload/test.js

test:
npm run test

Expand Down
121 changes: 103 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,38 +12,120 @@ No extra parsing needed.
![npm](https://img.shields.io/npm/dw/i18n)
[![Known Vulnerabilities][snyk-image]][snyk-url]
[![FOSSA Status][fossa-image]][fossa-url]
[![Greenkeeper badge][greenkeeper-image]][greenkeeper-url]

<p align="center">
<a href="https://www.buymeacoffee.com/mashpie" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" style="height: 51px !important;width: 217px !important; border-radius: 0.5rem !important;" width="217" height="51"></a><br>
...if you like :)
</p>

## Install
```sh
npm install i18n --save
```

## Test
```sh
npm test
## Synopsis

```js
const http = require('http')
const { I18n } = require('i18n')

const i18n = new I18n({
locales:['en', 'de'],
directory: __dirname + '/locales'
})

const app = http.createServer((req, res) => {
i18n.init(req, res);
res.end(res.__('Hello'));
});

app.listen(3000, '127.0.0.1');

```
This wires up a plain http server and return "Hello" or "Hallo" depending on browsers 'Accept-Language'. The first configured locale 'en' will default in case the browser doesn't include any of those locales in his request.

---

## Usage

With __0.12.0__ `i18n` now provides options to be used as instance or singleton.

- __Instances__ allow to work with multiple different configurations and encapsulate resources and states.
- __Singletons__ allow to share configuration, state and resources across multiple requires, modules or files.

Before __0.12.0__ _singleton usage_ was the only option. Instances give much more intuitive control and should be considered the "better practice" in complex setups.

### As Instance

Minimal example, just setup two locales and a project specific directory.

## Load
```js
// load modules
var express = require('express'),
i18n = require("i18n");
/**
* require I18n with capital I as constructor
*/
const { I18n } = require("i18n");

/**
* create a new instance with it's configuration
*/
const i18n = new I18n({
locales:['en', 'de'],
directory: __dirname + '/locales'
});
```

## Configure
Alternatively split creation and configuration, useful when split up into different modules for bootstrapping.

```js
/**
* require I18n with capital I as constructor
*/
const { I18n } = require("i18n");

/**
* create a new instance
*/
const i18n = new I18n();

/**
* later in code configure
*/
i18n.configure({
locales:['en', 'de'],
directory: __dirname + '/locales'
})
```

Minimal example, just setup two locales and a project specific directory

### As Singleton

Same Minimal example, just setup two locales and a project specific directory.

```js
const i18n = require("i18n");

/**
* configure shared state
*/
i18n.configure({
locales:['en', 'de'],
directory: __dirname + '/locales'
});
```
now you are ready to use a global `i18n.__('Hello')`.

## Example usage in global scope
Now you are ready to use a global `i18n.__('Hello')`.

Require `i18n`in another file reuses same configuration and shares state:

```js
const i18n = require("i18n");

module.exports = () => {
console.log(i18n.__('Hello'))
}
```

### CLI within global scope

In your cli, when not registered to a specific object:

Expand All @@ -54,7 +136,7 @@ var greeting = i18n.__('Hello');

> **Global** assumes you share a common state of localization in any time and any part of your app. This is usually fine in cli-style scripts. When serving responses to http requests you'll need to make sure that scope is __NOT__ shared globally but attached to your request object.
## Example usage in express.js
### Middleware in express.js

In an express app, you might use i18n.init to gather language settings of your visitors and also bind your helpers to response object honoring request objects locale, ie:

Expand Down Expand Up @@ -88,9 +170,9 @@ in your templates (depending on your template engine)
${__('Hello')}
```

## Examples for common setups
### Some examples for common setups

See [tested examples](https://github.com/mashpie/i18n-node/tree/master/examples) inside `/examples` for some inspiration in node 4.x / 5.x or browse these gists:
See [tested examples](https://github.com/mashpie/i18n-node/tree/master/examples) inside `/examples` for some inspiration in node and express or browse these gists:

> PLEASE NOTE: Those gist examples worked until node 0.12.x only
Expand All @@ -108,6 +190,7 @@ app.use(express.static(__dirname + '/www'));
app.use('/en', express.static(__dirname + '/www'));
app.use('/de', express.static(__dirname + '/www'));
```
---

## API

Expand Down Expand Up @@ -1014,6 +1097,11 @@ i18n.configure({
});
```

## Test
```sh
npm test
```

## Roadmap

* add a storage adapter (to support .yaml, .js, memory)
Expand Down Expand Up @@ -1041,6 +1129,3 @@ For current release notes see [GitHub Release Notes](https://github.com/mashpie/

[fossa-image]: https://app.fossa.com/api/projects/git%2Bgithub.com%2Fmashpie%2Fi18n-node.svg?type=shield
[fossa-url]: https://app.fossa.com/projects/git%2Bgithub.com%2Fmashpie%2Fi18n-node?ref=badge_shield

[greenkeeper-image]: https://badges.greenkeeper.io/mashpie/i18n-node.svg
[greenkeeper-url]: https://greenkeeper.io/
5 changes: 3 additions & 2 deletions examples/express4-cookie/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
var express = require('express');
var cookieParser = require('cookie-parser');
var url = require('url');
var i18n = require('../../i18n');
var i18n = require('../..'); // require('i18n')

i18n.configure({
locales: ['en', 'de', 'ar'],
cookie: 'yourcookiename',
directory: __dirname+'/locales'
directory: __dirname+'/locales',
updateFiles: false
});

var app = express();
Expand Down
5 changes: 5 additions & 0 deletions examples/express4-cookie/test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/**
* run like so:
* $ mocha --exit test.js
*/

require('./index');

var Browser = require('zombie'),
Expand Down
5 changes: 3 additions & 2 deletions examples/express4-setLocale/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
var express = require('express');
var url = require('url');
var i18n = require('../../i18n');
var i18n = require('../..'); // require('i18n')

// another 'global' object that is bound to i18n additionaly
// DANGER! this `funkyObject` is NOT concurrency aware,
Expand All @@ -10,7 +10,8 @@ var funkyObject = {};
i18n.configure({
locales: ['en', 'de', 'ar'],
register: funkyObject,
directory: __dirname + '/locales'
directory: __dirname + '/locales',
updateFiles: false
});

var app = express();
Expand Down
15 changes: 15 additions & 0 deletions examples/express4-setLocale/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "express4-setLocale",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.14.0"
}
}
3 changes: 2 additions & 1 deletion examples/node-http-autoreload/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@

// require modules
var http = require('http'),
i18n = require('../../i18n'),
i18n = require('../..'), // require('i18n')
url = require('url'),
app;

// minimal config
i18n.configure({
locales: ['en', 'de'],
directory: __dirname + '/locales',
updateFiles: false,
autoReload: true
});

Expand Down
5 changes: 3 additions & 2 deletions examples/node-http/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@

// require modules
var http = require('http'),
i18n = require('../../i18n'),
i18n = require('../..'), // require('i18n')
url = require('url'),
app;

// minimal config
i18n.configure({
locales: ['en', 'de'],
directory: __dirname + '/locales'
directory: __dirname + '/locales',
updateFiles: false
});

// simple server
Expand Down
34 changes: 34 additions & 0 deletions examples/singleton/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const i18n = require('../..')
const one = require('./modules/one')
const two = require('./modules/two')

i18n.configure({
locales:['en', 'de'],
directory: __dirname + '/locales'
});

// set to german
i18n.setLocale('de')

// will put 'Hallo'
console.log('index.js', i18n.__('Hello'))

// will also put 'Hallo'
one()

// will also put 'Hallo'
two()

// -------------------------------------------------

// set to german
i18n.setLocale('en')

// will put 'Hello'
console.log('index.js', i18n.__('Hello'))

// will also put 'Hello'
one()

// will also put 'Hello'
two()
4 changes: 4 additions & 0 deletions examples/singleton/locales/de.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"Hello World": "Hallo Welt",
"Hello": "Hallo"
}
4 changes: 4 additions & 0 deletions examples/singleton/locales/en.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"Hello World": "Hello World",
"Hello": "Hello"
}
5 changes: 5 additions & 0 deletions examples/singleton/modules/one.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const i18n = require('../../..')

module.exports = () => {
console.log('one.js', i18n.__('Hello'))
}
5 changes: 5 additions & 0 deletions examples/singleton/modules/two.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const i18n = require('../../..')

module.exports = () => {
console.log('two.js', i18n.__('Hello'))
}
18 changes: 15 additions & 3 deletions i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ var escapeRegExp = function(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
};

// exports an instance
module.exports = (function() {
// create constructor function
const i18n = function I18n(_OPTS = false) {

var MessageformatInstanceForLocale = {},
PluralsForLocale = {},
Expand Down Expand Up @@ -1269,6 +1269,18 @@ module.exports = (function() {
return value;
}

/**
* implicitly configure when created with given options
* @example
* const i18n = new I18n({
* locales: ['en', 'fr']
* });
*/
if(_OPTS) i18n.configure(_OPTS);


return i18n;

}());
};

module.exports = i18n;
13 changes: 12 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1 +1,12 @@
module.exports = require('./i18n');
const i18n = require('./i18n');

/**
* defaults to singleton, backward compat
*/
module.exports = i18n();

/**
* exports constructor with capital letter
*/
module.exports.I18n = i18n;

Loading

0 comments on commit 9cffae2

Please sign in to comment.