Skip to content

Commit

Permalink
fix: Allow processors to add scoped package imports
Browse files Browse the repository at this point in the history
  • Loading branch information
ExE-Boss committed Feb 1, 2020
1 parent 0c57f7e commit da7f757
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"use strict";
const path = require("path");
const { extname } = require("path");

function getDefault(dflt) {
switch (dflt.type) {
Expand Down Expand Up @@ -70,16 +70,20 @@ function toKey(type, func = "") {
return String(func + type).replace(/[./-]+/g, " ").trim().replace(/ /g, "_");
}

const PACKAGE_NAME_REGEX = /^(?:@([^/]+?)[/])?([^/]+?)$/u;

class RequiresMap extends Map {
constructor(ctx) {
super();
this.ctx = ctx;
}

add(type, func = "") {
const key = toKey(type, func);
add(name, func = "") {
const key = toKey(name, func);

const importPath = (type.includes("/") || type.startsWith(".")) && !path.extname(type) ? type + ".js" : type;
// If `name` is a package name or has a file extension, then use it as-is,
// otherwise append the `.js` file extension:
const importPath = PACKAGE_NAME_REGEX.test(name) || extname(name) ? name : `${name}.js`;
let req = `require(${JSON.stringify(importPath)})`;

if (func) {
Expand All @@ -93,8 +97,8 @@ class RequiresMap extends Map {
addRelative(type, func = "") {
const key = toKey(type, func);

const importPath = type.startsWith(".") ? type : `./${type}`;
let req = `require("${importPath}.js")`;
const path = type.startsWith(".") ? type : `./${type}`;
let req = `require("${path}.js")`;

if (func) {
req += `.${func}`;
Expand Down

0 comments on commit da7f757

Please sign in to comment.