Skip to content

Commit

Permalink
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 <opensource@fthiessen.de>
  • Loading branch information
susnux committed Jul 4, 2023
1 parent 2442b2d commit c7a5273
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
Expand Up @@ -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)

Expand Down Expand Up @@ -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'))
Expand Down

0 comments on commit c7a5273

Please sign in to comment.