diff --git a/lib/shared/require-or-import.js b/lib/shared/require-or-import.js index 6970ae42..aa1f2e9e 100644 --- a/lib/shared/require-or-import.js +++ b/lib/shared/require-or-import.js @@ -12,6 +12,35 @@ try { importESM = null; } +function getExt(path) { + // Remove trailling slash `/` + // and get gulpfile extension + var regex = /.([\w\d]+)\/*$/i; + return path.match(regex)[1]; +} + +function securePath(path) { + var pathStatsSync = require('fs').lstatSync; + var join = require('path').join; + + // Avoid ERR_UNSUPPORTED_DIR_IMPORT (NodeJs >= 12) + var validPath = pathStatsSync(path).isDirectory() ? + join(path, 'index.' + getExt(path)) : + path; + + // This is needed on Windows, because import() fails if providing a Windows file path. + return pathToFileURL(validPath); +} + +function onImportESM(path, callback) { + var safePath = securePath(path); + importESM(safePath) + .then(function(modules) { + callback(null, modules); + }) + .catch(callback); +} + function requireOrImport(path, callback) { var err = null; var cjs; @@ -19,10 +48,7 @@ function requireOrImport(path, callback) { cjs = require(path); } catch (e) { if (pathToFileURL && importESM && e.code === 'ERR_REQUIRE_ESM') { - // This is needed on Windows, because import() fails if providing a Windows file path. - var url = pathToFileURL(path); - importESM(url).then(function(esm) { callback(null, esm); }, callback); - return; + return onImportESM(path, callback); } err = e; }