Skip to content

Commit

Permalink
fix(webpack): skip readFileSync if not defined (#117)
Browse files Browse the repository at this point in the history
  • Loading branch information
bcoe authored Apr 5, 2021
1 parent c755582 commit 6966fa9
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 51 deletions.
31 changes: 17 additions & 14 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ class Y18N {

// if a %d placeholder is provided, add quantity
// to the arguments expanded by util.format.
var values: (string|number)[] = [str]
const values: (string|number)[] = [str]
if (~str.indexOf('%d')) values.push(quantity)

return shim.format.apply(shim.format, values.concat(args))
Expand All @@ -147,7 +147,7 @@ class Y18N {
_taggedLiteral (parts: string[], ...args: string[]) {
let str = ''
parts.forEach(function (part, i) {
var arg = args[i + 1]
const arg = args[i + 1]
str += part
if (typeof arg !== 'undefined') {
str += '%s'
Expand All @@ -162,16 +162,16 @@ class Y18N {
}

_processWriteQueue () {
var _this = this
var work = this.writeQueue[0]
const _this = this
const work = this.writeQueue[0]

// destructure the enqueued work.
var directory = work.directory
var locale = work.locale
var cb = work.cb
const directory = work.directory
const locale = work.locale
const cb = work.cb

var languageFile = this._resolveLocaleFile(directory, locale)
var serializedLocale = JSON.stringify(this.cache[locale], null, 2)
const languageFile = this._resolveLocaleFile(directory, locale)
const serializedLocale = JSON.stringify(this.cache[locale], null, 2)

shim.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err: Error) {
_this.writeQueue.shift()
Expand All @@ -181,11 +181,14 @@ class Y18N {
}

_readLocaleFile () {
var localeLookup = {}
var languageFile = this._resolveLocaleFile(this.directory, this.locale)
let localeLookup = {}
const languageFile = this._resolveLocaleFile(this.directory, this.locale)

try {
localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, 'utf-8'))
// When using a bundler such as webpack, readFileSync may not be defined:
if (shim.fs.readFileSync) {
localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, 'utf-8'))
}
} catch (err) {
if (err instanceof SyntaxError) {
err.message = 'syntax error in ' + languageFile
Expand All @@ -199,10 +202,10 @@ class Y18N {
}

_resolveLocaleFile (directory: string, locale: string) {
var file = shim.resolve(directory, './', locale + '.json')
let file = shim.resolve(directory, './', locale + '.json')
if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) {
// attempt fallback to language only
var languageFile = shim.resolve(directory, './', locale.split('_')[0] + '.json')
const languageFile = shim.resolve(directory, './', locale.split('_')[0] + '.json')
if (this._fileExistsSync(languageFile)) file = languageFile
}
return file
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@
"author": "Ben Coe <bencoe@gmail.com>",
"main": "./build/index.cjs",
"scripts": {
"check": "standardx '**/*.ts' '**/*.cjs' '**/*.mjs'",
"fix": "standardx --fix '**/*.ts' '**/*.cjs' '**/*.mjs'",
"check": "standardx **/*.ts **/*.cjs **/*.mjs",
"fix": "standardx --fix **/*.ts **/*.cjs **/*.mjs",
"pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs",
"test": "c8 --reporter=text --reporter=html mocha test/*.cjs",
"test:esm": "c8 --reporter=text --reporter=html mocha test/esm/*.mjs",
Expand All @@ -50,7 +50,7 @@
"mocha": "^8.0.0",
"rimraf": "^3.0.2",
"rollup": "^2.26.10",
"standardx": "^6.0.0",
"standardx": "^7.0.0",
"ts-transform-default-export": "^1.0.2",
"typescript": "^4.0.0"
},
Expand Down
68 changes: 34 additions & 34 deletions test/y18n-test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ describe('y18n', function () {
describe('_readLocaleFile', function () {
it('throws a helpful error if language file has invalid syntax', function () {
expect(function () {
var __ = y18n({
const __ = y18n({
locale: 'bad-locale',
directory: path.join(__dirname, 'locales')
}).__
Expand All @@ -31,30 +31,30 @@ describe('y18n', function () {

describe('__', function () {
it('can be used as a tag for template literals', function () {
var __ = y18n({
const __ = y18n({
locale: 'pirate',
directory: path.join(__dirname, 'locales')
}).__

__`Hi, ${'Ben'} ${'Coe'}!`.should.equal('Yarr! Shiver me timbers, why \'tis Ben Coe!')
})
it('can be used as a tag for template literals with falsy arguments', function () {
var __ = y18n({
const __ = y18n({
locale: 'pirate',
directory: path.join(__dirname, 'locales')
}).__
__`Hi, ${'Ben'} ${''}!`.should.equal('Yarr! Shiver me timbers, why \'tis Ben !')
})
it('uses replacements from the default locale if none is configured', function () {
var __ = y18n({
const __ = y18n({
directory: path.join(__dirname, 'locales')
}).__

__('Hello').should.equal('Hello!')
})

it('uses replacements from the configured locale', function () {
var __ = y18n({
const __ = y18n({
locale: 'pirate',
directory: path.join(__dirname, 'locales')
}).__
Expand All @@ -63,7 +63,7 @@ describe('y18n', function () {
})

it('uses language file if language_territory file does not exist', function () {
var __ = y18n({
const __ = y18n({
locale: 'pirate_JM',
directory: path.join(__dirname, 'locales')
}).__
Expand All @@ -72,7 +72,7 @@ describe('y18n', function () {
})

it('does not fallback to language file if fallbackToLanguage is false', function () {
var __ = y18n({
const __ = y18n({
locale: 'pirate_JM',
fallbackToLanguage: false,
updateFiles: false,
Expand All @@ -83,7 +83,7 @@ describe('y18n', function () {
})

it('uses strings as given if no matching locale files found', function () {
var __ = y18n({
const __ = y18n({
locale: 'zz_ZZ',
updateFiles: false,
directory: path.join(__dirname, 'locales')
Expand All @@ -93,7 +93,7 @@ describe('y18n', function () {
})

it('expands arguments into %s placeholders', function () {
var __ = y18n({
const __ = y18n({
directory: path.join(__dirname, 'locales')
}).__

Expand All @@ -108,7 +108,7 @@ describe('y18n', function () {
})

it('returns the word immediately', function () {
var __ = y18n({
const __ = y18n({
locale: 'fr',
directory: path.join(__dirname, 'locales')
}).__
Expand All @@ -117,13 +117,13 @@ describe('y18n', function () {
})

it('writes new word to locale file if updateFiles is true', function (done) {
var __ = y18n({
const __ = y18n({
locale: 'fr_FR',
directory: path.join(__dirname, 'locales')
}).__

__('banana', function (err) {
var locale = JSON.parse(fs.readFileSync('./test/locales/fr_FR.json', 'utf-8'))
const locale = JSON.parse(fs.readFileSync('./test/locales/fr_FR.json', 'utf-8'))
locale.banana.should.equal('banana')
return done(err)
})
Expand All @@ -132,14 +132,14 @@ describe('y18n', function () {
it('writes new word to language file if language_territory file does not exist', function (done) {
fs.writeFileSync('./test/locales/fr.json', '{"meow": "le meow"}', 'utf-8')

var __ = y18n({
const __ = y18n({
locale: 'fr_FR',
directory: path.join(__dirname, 'locales')
}).__

__('meow').should.equal('le meow')
__('banana', function (err) {
var locale = JSON.parse(fs.readFileSync('./test/locales/fr.json', 'utf-8'))
const locale = JSON.parse(fs.readFileSync('./test/locales/fr.json', 'utf-8'))
locale.banana.should.equal('banana')
return done(err)
})
Expand All @@ -148,20 +148,20 @@ describe('y18n', function () {
it('writes word to missing locale file, if no fallback takes place', function (done) {
fs.writeFileSync('./test/locales/fr.json', '{"meow": "le meow"}', 'utf-8')

var __ = y18n({
const __ = y18n({
locale: 'fr_FR',
fallbackToLanguage: false,
directory: path.join(__dirname, 'locales')
}).__

__('banana', function (err) {
// 'banana' should be written to fr_FR.json
var locale = JSON.parse(fs.readFileSync('./test/locales/fr_FR.json', 'utf-8'))
const locale = JSON.parse(fs.readFileSync('./test/locales/fr_FR.json', 'utf-8'))
locale.should.deep.equal({
banana: 'banana'
})
// fr.json should remain untouched
var frJson = JSON.parse(fs.readFileSync('./test/locales/fr.json', 'utf-8'))
const frJson = JSON.parse(fs.readFileSync('./test/locales/fr.json', 'utf-8'))
frJson.should.deep.equal({
meow: 'le meow'
})
Expand All @@ -170,7 +170,7 @@ describe('y18n', function () {
})

it('handles enqueuing multiple writes at the same time', function (done) {
var __ = y18n({
const __ = y18n({
locale: 'fr',
directory: path.join(__dirname, 'locales')
}).__
Expand All @@ -179,7 +179,7 @@ describe('y18n', function () {
__('banana', function () {
__('foo')
__('bar', function (err) {
var locale = JSON.parse(fs.readFileSync('./test/locales/fr.json', 'utf-8'))
const locale = JSON.parse(fs.readFileSync('./test/locales/fr.json', 'utf-8'))
locale.apple.should.equal('apple')
locale.banana.should.equal('banana')
locale.foo.should.equal('foo')
Expand All @@ -190,7 +190,7 @@ describe('y18n', function () {
})

it('does not write the locale file if updateFiles is false', function (done) {
var __ = y18n({
const __ = y18n({
locale: 'fr',
updateFiles: false,
directory: path.join(__dirname, 'locales')
Expand All @@ -206,31 +206,31 @@ describe('y18n', function () {

describe('__n', function () {
it('uses the singular form if quantity is 1', function () {
var __n = y18n({
const __n = y18n({
directory: path.join(__dirname, 'locales')
}).__n

__n('%d cat', '%d cats', 1).should.equal('1 cat')
})

it('uses the plural form if quantity is greater than 1', function () {
var __n = y18n({
const __n = y18n({
directory: path.join(__dirname, 'locales')
}).__n

__n('%d cat', '%d cats', 2).should.equal('2 cats')
})

it('allows additional arguments to be printed', function () {
var __n = y18n({
const __n = y18n({
directory: path.join(__dirname, 'locales')
}).__n

__n('%d %s cat', '%d %s cats', 2, 'black').should.equal('2 black cats')
})

it('allows an alternative locale to be set', function () {
var __n = y18n({
const __n = y18n({
locale: 'pirate',
directory: path.join(__dirname, 'locales')
}).__n
Expand All @@ -241,12 +241,12 @@ describe('y18n', function () {

// See: https://github.com/bcoe/yargs/pull/210
it('allows a quantity placeholder to be provided in the plural but not singular form', function () {
var __n = y18n({
const __n = y18n({
directory: path.join(__dirname, 'locales')
}).__n

var singular = __n('There is one monkey in the %s', 'There are %d monkeys in the %s', 1, 'tree')
var plural = __n('There is one monkey in the %s', 'There are %d monkeys in the %s', 3, 'tree')
const singular = __n('There is one monkey in the %s', 'There are %d monkeys in the %s', 1, 'tree')
const plural = __n('There is one monkey in the %s', 'There are %d monkeys in the %s', 3, 'tree')

singular.should.equal('There is one monkey in the tree')
plural.should.equal('There are 3 monkeys in the tree')
Expand All @@ -260,7 +260,7 @@ describe('y18n', function () {
})

it('returns the pluralization immediately', function () {
var __n = y18n({
const __n = y18n({
locale: 'fr',
directory: path.join(__dirname, 'locales')
}).__n
Expand All @@ -269,21 +269,21 @@ describe('y18n', function () {
})

it('writes to the locale file if updateFiles is true', function (done) {
var __n = y18n({
const __n = y18n({
locale: 'fr',
directory: path.join(__dirname, 'locales')
}).__n

__n('%d apple %s', '%d apples %s', 2, 'dude', function (err) {
var locale = JSON.parse(fs.readFileSync('./test/locales/fr.json', 'utf-8'))
const locale = JSON.parse(fs.readFileSync('./test/locales/fr.json', 'utf-8'))
locale['%d apple %s'].one.should.equal('%d apple %s')
locale['%d apple %s'].other.should.equal('%d apples %s')
return done(err)
})
})

it('does not write the locale file if updateFiles is false', function (done) {
var __n = y18n({
const __n = y18n({
locale: 'fr',
updateFiles: false,
directory: path.join(__dirname, 'locales')
Expand All @@ -299,7 +299,7 @@ describe('y18n', function () {

describe('setLocale', function () {
it('switches the locale', function () {
var i18n = y18n({
const i18n = y18n({
directory: path.join(__dirname, 'locales')
})

Expand All @@ -317,7 +317,7 @@ describe('y18n', function () {
})

it('updates the locale with the new lookups provided', function () {
var i18n = y18n({
const i18n = y18n({
locale: 'fr',
directory: path.join(__dirname, 'locales')
})
Expand All @@ -332,7 +332,7 @@ describe('y18n', function () {
it('loads the locale from disk prior to updating the map', function () {
fs.writeFileSync('./test/locales/fr.json', '{"meow": "le meow"}', 'utf-8')

var i18n = y18n({
const i18n = y18n({
locale: 'fr',
directory: path.join(__dirname, 'locales')
})
Expand Down

0 comments on commit 6966fa9

Please sign in to comment.