Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ERR_UNSUPPORTED_DIR_IMPORT for gulpfile.mjs #217

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions lib/shared/require-or-import.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,43 @@ 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;
try {
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;
}
Expand Down