summaryrefslogtreecommitdiff
path: root/src/compiler/transform/module-scripts.ts
blob: aff1ec4f6da193c22a4e521f7bdb41c32d8021de (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import type { Transformer } from '../../@types/transformer';
import type { CompileOptions } from '../../@types/compiler';

import path from 'path';
import { getAttrValue, setAttrValue } from '../../ast.js';

/** Transform <script type="module"> */
export default function ({ compileOptions, filename }: { compileOptions: CompileOptions; filename: string; fileID: string }): Transformer {
  const { astroConfig } = compileOptions;
  const { astroRoot } = astroConfig;
  const fileUrl = new URL(`file://${filename}`);

  return {
    visitors: {
      html: {
        Element: {
          enter(node) {
            let name = node.name;
            if (name !== 'script') {
              return;
            }

            let type = getAttrValue(node.attributes, 'type');
            if (type !== 'module') {
              return;
            }

            let src = getAttrValue(node.attributes, 'src');
            if (!src || !src.startsWith('.')) {
              return;
            }

            const srcUrl = new URL(src, fileUrl);
            const fromAstroRoot = path.posix.relative(astroRoot.pathname, srcUrl.pathname);
            const absoluteUrl = `/_astro/${fromAstroRoot}`;
            setAttrValue(node.attributes, 'src', absoluteUrl);
          },
        },
      },
    },
    async finalize() {},
  };
}