Page Menu
Home
Sealhub
Search
Configure Global Search
Log In
Files
F996304
remove-named-imports.js
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
2 KB
Referenced Files
None
Subscribers
None
remove-named-imports.js
View Options
import
fs
from
"node:fs/promises"
;
import
{
extname
}
from
"node:path"
;
const
generate_names
=
(
function
*
generate_names
()
{
const
base_name
=
"____unique_import_"
;
let
count
=
0
;
while
(
true
)
{
yield
`
${
base_name
}${
count
}
`
;
count
++
;
}
})();
export
function
removeNamedImports
(
content
)
{
const
named_and_default_regex
=
/^import\s+((\S+),\s+)?({\s*[^}]+})\s+from\s+("[^"]+");\s*$/gm
;
return
content
.
replace
(
named_and_default_regex
,
(
_
,
default_import_name
,
__
,
all_named
,
module_path
)
=>
{
/* eslint-disable */
const
new_name
=
generate_names
.
next
().
value
;
const
result
=
`import * as
${
new_name
}
from
${
module_path
}${
default_import_name
?
`; const
${
default_import_name
.
replace
(
","
,
""
)
}
=
${
new_name
}
.default ||
${
new_name
}
;`
:
""
}
;`
+
all_named
.
match
(
/[a-zA-Z_$][^,}]+/g
)
.
map
((
importname
)
=>
{
if
(
importname
.
startsWith
(
"default as"
))
{
return
`const
${
importname
.
replace
(
"default as "
,
""
)
}
=
${
new_name
}
?.default ||
${
new_name
}
;`
;
}
if
(
importname
.
match
(
/([^{]*)\sas\s([^}]*)/
))
{
// is "import {asdfas as somethong_else}
const
[
_
,
original
,
named
]
=
importname
.
match
(
/([^{]*)\sas\s([^}]*)/
);
return
`const
${
named
}
=
${
new_name
}
?.default?.
${
original
}
||
${
new_name
}
?.
${
original
}
`
;
}
return
`const
${
importname
}
=
${
new_name
}
?.default?.
${
importname
}
||
${
new_name
}
?.
${
importname
}
;`
;
})
.
join
(
"; "
);
return
result
;
/* eslint-enable */
}
);
}
export
const
remove_named_imports_plugin
=
{
name
:
"remove-named-imports"
,
// named imports sometime cause some esm incompatibilities, like the "is a CommonJS module, which may not support all module.exports as named exports." error
setup
(
build
)
{
build
.
onLoad
({
filter
:
/\.[t]sx?$/
},
async
({
path
})
=>
{
const
content
=
await
fs
.
readFile
(
path
,
"utf-8"
);
const
contents
=
removeNamedImports
(
content
);
return
{
pluginData
:
{
contents
,
},
loader
:
extname
(
path
)
===
".tsx"
?
"tsx"
:
"ts"
,
};
});
},
};
File Metadata
Details
Attached
Mime Type
text/x-java
Expires
Tue, Dec 24, 14:02 (17 h, 18 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
556439
Default Alt Text
remove-named-imports.js (2 KB)
Attached To
Mode
rSGEN sealgen
Attached
Detach File
Event Timeline
Log In to Comment