|
1 | 1 | import { builtinModules } from 'node:module' |
2 | 2 | import type { Plugin } from 'rolldown' |
3 | 3 |
|
4 | | -const modulesWithoutProtocol = builtinModules.filter( |
5 | | - (mod) => !mod.startsWith('node:'), |
6 | | -) |
7 | | - |
8 | 4 | /** |
9 | 5 | * The `node:` protocol was added in Node.js v14.18.0. |
10 | 6 | * @see https://nodejs.org/api/esm.html#node-imports |
11 | 7 | */ |
12 | 8 | export function NodeProtocolPlugin(nodeProtocolOption: 'strip' | true): Plugin { |
13 | | - if (nodeProtocolOption === 'strip') { |
14 | | - const regex = new RegExp(`^node:(${modulesWithoutProtocol.join('|')})$`) |
15 | | - |
16 | | - return { |
17 | | - name: 'tsdown:node-protocol:strip', |
18 | | - resolveId: { |
19 | | - order: 'pre', |
20 | | - filter: { id: regex }, |
21 | | - handler(id) { |
22 | | - return { |
23 | | - id: id.slice(5), // strip the `node:` prefix |
24 | | - external: true, |
25 | | - moduleSideEffects: false, |
26 | | - } |
27 | | - }, |
28 | | - }, |
29 | | - } |
30 | | - } |
31 | | - |
32 | | - // create regex from builtin modules |
33 | | - // filter without `node:` prefix |
34 | | - const builtinModulesRegex = new RegExp( |
35 | | - `^(${modulesWithoutProtocol.join('|')})$`, |
| 9 | + const modulesWithoutProtocol = builtinModules.filter( |
| 10 | + (mod) => !mod.startsWith('node:'), |
36 | 11 | ) |
37 | 12 |
|
38 | 13 | return { |
39 | | - name: 'tsdown:node-protocol:add', |
| 14 | + name: `tsdown:node-protocol`, |
40 | 15 | resolveId: { |
41 | 16 | order: 'pre', |
42 | | - filter: { id: builtinModulesRegex }, |
43 | | - handler(id) { |
44 | | - return { |
45 | | - id: `node:${id}`, |
46 | | - external: true, |
47 | | - moduleSideEffects: false, |
48 | | - } |
| 17 | + filter: { |
| 18 | + id: |
| 19 | + nodeProtocolOption === 'strip' |
| 20 | + ? new RegExp(`^node:(${modulesWithoutProtocol.join('|')})$`) |
| 21 | + : new RegExp(`^(${modulesWithoutProtocol.join('|')})$`), |
49 | 22 | }, |
| 23 | + handler: |
| 24 | + nodeProtocolOption === 'strip' |
| 25 | + ? (id) => { |
| 26 | + return { |
| 27 | + // strip the `node:` prefix |
| 28 | + id: id.slice(5), |
| 29 | + external: true, |
| 30 | + moduleSideEffects: false, |
| 31 | + } |
| 32 | + } |
| 33 | + : (id) => { |
| 34 | + return { |
| 35 | + id: `node:${id}`, |
| 36 | + external: true, |
| 37 | + moduleSideEffects: false, |
| 38 | + } |
| 39 | + }, |
50 | 40 | }, |
51 | 41 | } |
52 | 42 | } |
0 commit comments