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

feat: import css or json from import-maps or http #73

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
56 changes: 55 additions & 1 deletion src/output/moduleCompiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,61 @@ function processModule(store: Store, src: string, filename: string) {
// import * as ok from 'foo' --> ok -> __import_foo__
if (node.type === 'ImportDeclaration') {
const source = node.source.value
if (source.startsWith('./')) {
if (source.endsWith('?raw')) {
const url = source.slice(0, -4)
s.overwrite(
node.start!,
node.end!,
`const ${node.specifiers[0].local.name} = await (await fetch(${
url.startsWith('http')
? `'${url}'`
: `import.meta.resolve('${url}')`
})).text()`
)
} else if (source.endsWith('.css')) {
// import 'foo/style.css' --> <link rel="stylesheet" href="" />, href is import.meta.resolve('foo/style.css')
// import 'http://127.0.0.1/style.css' --> <link rel="stylesheet" href="http://127.0.0.1/style.css" />
s.overwrite(
node.start!,
node.end!,
`if(true){
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = ${
source.startsWith('http')
? `'${source}'`
: `import.meta.resolve('${source}')`
};
document.head.appendChild(link);
}`
)
} else if (source.endsWith('.json')) {
// import data from 'foo/data.json' --> const data = await (await fetch(import.meta.resolve('foo/data.json'))).json()
s.overwrite(
node.start!,
node.end!,
`const ${node.specifiers[0].local.name} = await (await fetch(${
source.startsWith('http')
? `'${source}'`
: `import.meta.resolve('${source}'))`
})).json()`
)
} else if (
source.match(
/\.(ttf|otf|woff2?|eot|jpe?g|png|jfif|pjpeg|pjp|gif|svg|ico|webp|avif|mp4|webm|ogg|mp3|wav|flac|aac)$/
)
) {
// import font from 'foo/dont.ttf' --> const font = import.meta.resolve('foo/dont.ttf')
s.overwrite(
node.start!,
node.end!,
`const ${node.specifiers[0].local.name} = ${
source.startsWith('http')
? `'${source}'`
: `import.meta.resolve('${source}')`
}`
)
} else if (source.startsWith('./')) {
const importId = defineImport(node, node.source.value)
for (const spec of node.specifiers) {
if (spec.type === 'ImportSpecifier') {
Expand Down