Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: Make sure the translations helper can be imported by vite, web…
Browse files Browse the repository at this point in the history
…pack and cypress

When imported in vite config it will be executed in ESM context where dynamic require of modules is not available.
But when converted to ES module it works in vite config + webpack config, but not in Cypress config.
Because our package type is `commonjs` so Typescript files are executed as CommonJS Typescript, so the Cypress config can not require "import" an ES module.

Solutions: Either set out package to `type: "module"` or as done here rewrite all require calls to dynamic import which is available on CommonJS *and* ES module.

Signed-off-by: Ferdinand Thiessen <[email protected]>
susnux committed Jul 11, 2023

Verified

This commit was signed with the committer’s verified signature.
doppins-bot Doppins
1 parent b9330bd commit 96663e6
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions build/translations.js
Original file line number Diff line number Diff line change
@@ -19,15 +19,19 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
const { join, basename } = require('path')
const fs = require('fs/promises')
const gettextParser = require('gettext-parser')

// https://github.com/alexanderwallin/node-gettext#usage
// https://github.com/alexanderwallin/node-gettext#load-and-add-translations-from-mo-or-po-files
const parseFile = async (fileName) => {
// We need to import dependencies dynamically to support this module to be imported by vite and to be required by Cypress
// If we use require, vite will fail with 'Dynamic require of "path" is not supported'
// If we convert it to an ES module, webpack and vite are fine but Cypress will fail because it can not handle ES imports in Typescript configs in commonjs packages
const { basename } = await import('path')
const { readFile } = await import('fs/promises')
const gettextParser = await import('gettext-parser')

const locale = basename(fileName).slice(0, -'.pot'.length)
const po = await fs.readFile(fileName)
const po = await readFile(fileName)

const json = gettextParser.po.parse(po)

@@ -56,7 +60,9 @@ const parseFile = async (fileName) => {
}

const loadTranslations = async (baseDir) => {
const files = await fs.readdir(baseDir)
const { join } = await import('path')
const { readdir } = await import('fs/promises')
const files = await readdir(baseDir)

const promises = files
.filter(name => name !== 'messages.pot' && name.endsWith('.pot'))

0 comments on commit 96663e6

Please sign in to comment.