|
| 1 | +import fs from 'node:fs' |
| 2 | +import path from 'node:path' |
1 | 3 | import replace from '@rollup/plugin-replace' |
| 4 | +import { parse } from '@babel/parser' |
| 5 | + |
| 6 | +export function treeShakingPlugin(registryPath) { |
| 7 | + if (!registryPath) { |
| 8 | + return null |
| 9 | + } |
2 | 10 |
|
3 | | -export function treeShakingPlugin(removedRegistry) { |
4 | 11 | const envReplace = {} |
5 | | - Object.entries(removedRegistry).forEach(([key, value]) => { |
6 | | - envReplace[`__TINY_ENGINE_REMOVED_REGISTRY["${key}"]`] = value |
7 | | - }) |
8 | | - return replace({ |
9 | | - values: { |
10 | | - ...envReplace |
11 | | - }, |
12 | | - delimiters: ['', ''] |
13 | | - }) |
| 12 | + const filePath = path.resolve(process.cwd(), registryPath) |
| 13 | + |
| 14 | + if (!fs.existsSync(filePath)) { |
| 15 | + // TODO: 测试可否返回 null |
| 16 | + return null |
| 17 | + } |
| 18 | + |
| 19 | + try { |
| 20 | + const fileContent = fs.readFileSync(filePath, 'utf-8') |
| 21 | + const ast = parse(fileContent, { sourceType: 'module' }) |
| 22 | + const commentPattern = /#__TINY_ENGINE_TREE_SHAKING__:\s*(?<value>true|false)/ |
| 23 | + |
| 24 | + ast.program.body.forEach((item) => { |
| 25 | + // 过滤默认导出 且导出类型为 object |
| 26 | + if (item.type === 'ExportDefaultDeclaration' && item.declaration?.type === 'ObjectExpression') { |
| 27 | + item.declaration.properties.forEach((propertyItem) => { |
| 28 | + // 是属性 且 key 为 string |
| 29 | + if (propertyItem.type === 'ObjectProperty' && propertyItem.key?.type === 'StringLiteral') { |
| 30 | + const key = propertyItem.key.value |
| 31 | + // 有 comment,解析 comment。 |
| 32 | + // 通过 comment 指定 treeshaking,优先以 comment 为标准 |
| 33 | + if (propertyItem.leadingComments?.length) { |
| 34 | + // TODO: 测试多行匹配 |
| 35 | + // TODO: 需要确认是仅解析前面一个注释,还是解析所有注释 |
| 36 | + for (const commentItem of propertyItem.leadingComments) { |
| 37 | + const match = commentItem.value.match(commentPattern) |
| 38 | + |
| 39 | + if (!match) { |
| 40 | + continue |
| 41 | + } |
| 42 | + |
| 43 | + if (match.groups.value === 'true') { |
| 44 | + envReplace[`__TINY_ENGINE_REMOVED_REGISTRY["${key}"]`] = false |
| 45 | + } |
| 46 | + |
| 47 | + return |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + // 注册表注释了插件,默认 tree-shaking, |
| 52 | + if (propertyItem.value.type === 'BooleanLiteral' && propertyItem.value.value === false) { |
| 53 | + envReplace[`__TINY_ENGINE_REMOVED_REGISTRY["${key}"]`] = false |
| 54 | + } |
| 55 | + } |
| 56 | + }) |
| 57 | + } |
| 58 | + }) |
| 59 | + |
| 60 | + return replace({ |
| 61 | + values: { |
| 62 | + ...envReplace |
| 63 | + }, |
| 64 | + delimiters: ['', ''] |
| 65 | + }) |
| 66 | + } catch (error) { |
| 67 | + const logger = console |
| 68 | + logger.warn('[]') |
| 69 | + } |
| 70 | + |
| 71 | + return null |
14 | 72 | } |
0 commit comments