Skip to content

Commit eafc329

Browse files
committed
fix: Make sure the translations helper can be imported by vite, webpack 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>
1 parent 8a3037a commit eafc329

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

build/translations.js

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,19 @@
1919
* along with this program. If not, see <http://www.gnu.org/licenses/>.
2020
*
2121
*/
22-
const { join, basename } = require('path')
23-
const fs = require('fs/promises')
24-
const gettextParser = require('gettext-parser')
2522

2623
// https://github.com/alexanderwallin/node-gettext#usage
2724
// https://github.com/alexanderwallin/node-gettext#load-and-add-translations-from-mo-or-po-files
2825
const parseFile = async (fileName) => {
26+
// We need to import dependencies dynamically to support this module to be imported by vite and to be required by Cypress
27+
// If we use require, vite will fail with 'Dynamic require of "path" is not supported'
28+
// 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
29+
const { basename } = await import('path')
30+
const { readFile } = await import('fs/promises')
31+
const gettextParser = await import('gettext-parser')
32+
2933
const locale = basename(fileName).slice(0, -'.pot'.length)
30-
const po = await fs.readFile(fileName)
34+
const po = await readFile(fileName)
3135

3236
const json = gettextParser.po.parse(po)
3337

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

5862
const loadTranslations = async (baseDir) => {
59-
const files = await fs.readdir(baseDir)
63+
const { join } = await import('path')
64+
const { readdir } = await import('fs/promises')
65+
const files = await readdir(baseDir)
6066

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

0 commit comments

Comments
 (0)