From 67c16a9b4519398692c95d4234f7fb0df18d9f1c Mon Sep 17 00:00:00 2001 From: Dan Burzo Date: Thu, 2 Sep 2021 15:05:41 +0300 Subject: [PATCH] Add support for async parse in loader --- index.test.js | 10 +++------- loader.js | 27 +++++++++++++++++---------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/index.test.js b/index.test.js index e8b6661..d949b82 100644 --- a/index.test.js +++ b/index.test.js @@ -55,7 +55,7 @@ tape('config', test => { t('Hello World'); }, /No translation found/); config({ - log: function() { + log: function () { throw new Error('CustomError'); } }); @@ -73,12 +73,8 @@ tape('config', test => { }); tape('loader', test => { - let expected = `var nano = require('nano-i18n'); -var res = {}; -res[nano.k\`Hello, $\{'World'}\`] = nano.v\`Salut, $\{0}\`; -res[nano.k\`Simple String\`] = nano.v\`Șir Simplu\`; -module.exports = res;`; - + let expected = + "var nano = require('nano-i18n'); \nvar res = {};\nres[nano.k`Hello, ${'World'}`] = nano.v`Salut, ${0}`;\nres[nano.k`Simple String`] = nano.v`Șir Simplu`;\nmodule.exports = res;"; test.equal( loader([ { key: "Hello, ${'World'}", val: 'Salut, ${0}' }, diff --git a/loader.js b/loader.js index 461123c..59407c9 100644 --- a/loader.js +++ b/loader.js @@ -1,18 +1,25 @@ /* Webpack loader */ -module.exports = function(text) { +const out = obj => `var nano = require('nano-i18n'); +var res = {}; +${obj.map(entry => `res[nano.k\`${entry.key}\`] = nano.v\`${entry.val}\`;`).join('\n')} +module.exports = res;`; + +module.exports = function (text) { if (typeof this.cacheable === 'function') { this.cacheable(); } - - let obj = text; - if (typeof this.query === 'object' && typeof this.query.parse === 'function') { - obj = this.query.parse(text); + let p = + typeof this.query === 'object' && typeof this.query.parse === 'function' + ? this.query.parse(text) + : text; + if (typeof this.async === 'function') { + let cb = this.async(); + Promise.resolve(p).then(obj => { + cb(null, out(obj)); + }); + } else { + return out(p); } - - return `var nano = require('nano-i18n'); -var res = {}; -${obj.map(entry => `res[nano.k\`${entry.key}\`] = nano.v\`${entry.val}\`;`).join('\n')} -module.exports = res;`; };