import-maps-webpack-plugin
Version:
A plugin for providing static import maps support to Webpack.
74 lines • 2.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveImportMap = exports.getImportFor = exports.getHashFor = exports.getPackageDir = void 0;
var fs_1 = require("fs");
var path_1 = require("path");
function getSourcePath(root, file) {
return "../" + path_1.relative(root, file);
}
function resolvePath(root, dir, file) {
if (file.startsWith('/')) {
return getSourcePath(root, "." + file);
}
else {
return getSourcePath(root, path_1.resolve(dir, file));
}
}
function getPackageJson(dir) {
if (dir) {
var path = path_1.resolve(dir, 'package.json');
return require(path);
}
return {};
}
function getPackageDir(dir) {
var path = path_1.resolve(dir, 'package.json');
if (fs_1.existsSync(path)) {
return dir;
}
var upper = path_1.resolve(dir, '..');
if (upper !== dir) {
return getPackageDir(upper);
}
return undefined;
}
exports.getPackageDir = getPackageDir;
function getHashFor(root, dir, file) {
if (!file.startsWith('http:') && !file.startsWith('https:')) {
var path = resolvePath(root, dir, file);
return "require.resolveWeak(" + JSON.stringify(path) + ")";
}
else {
return JSON.stringify(file);
}
}
exports.getHashFor = getHashFor;
function getImportFor(root, dir, file) {
if (!file.startsWith('http:') && !file.startsWith('https:')) {
var path = resolvePath(root, dir, file);
return "import(" + JSON.stringify(path) + ")";
}
else {
return "new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(\"GET\", " + JSON.stringify(file) + ");\n xhr.onreadystatechange = function() {\n if (xhr.readyState === 4) {\n if (xhr.status === 200) {\n const result = {\n exports: {},\n };\n const f = new Function('module', 'exports', 'require', xhr.responseText);\n f(result, result.exports, require);\n resolve(result.exports);\n } else {\n reject(xhr.statusText);\n }\n }\n };\n xhr.send();\n })";
}
}
exports.getImportFor = getImportFor;
function resolveImportMap(dir) {
var pckg = getPackageJson(dir);
var map = pckg.importmap;
if (typeof map === 'string') {
var target = path_1.resolve(dir, map);
if (fs_1.existsSync(target)) {
return require(target);
}
else {
console.warn("Could not find the referenced import maps \"" + map + "\" from " + dir + ". Skipping.");
}
}
else if (typeof map === 'object') {
return map;
}
return undefined;
}
exports.resolveImportMap = resolveImportMap;
//# sourceMappingURL=helpers.js.map