@@ -54,7 +54,7 @@ export function remarkCodeHike(
54
54
addConfig ( tree , config )
55
55
56
56
if ( config . autoImport && ! hasCodeHikeImport ) {
57
- addImportNode ( tree )
57
+ addSmartImport ( tree , usage )
58
58
}
59
59
}
60
60
}
@@ -107,6 +107,101 @@ function addConfig(
107
107
} )
108
108
}
109
109
110
+ function addSmartImport ( tree : SuperNode , usage : string [ ] ) {
111
+ const specifiers = [
112
+ "annotations" ,
113
+ ...usage . map ( name => name . slice ( "CH." . length ) ) ,
114
+ ]
115
+
116
+ tree . children . unshift ( {
117
+ type : "mdxjsEsm" ,
118
+ value : `export const CH = { ${ specifiers . join ( ", " ) } }` ,
119
+ data : {
120
+ estree : {
121
+ type : "Program" ,
122
+ body : [
123
+ {
124
+ type : "ExportNamedDeclaration" ,
125
+ declaration : {
126
+ type : "VariableDeclaration" ,
127
+ declarations : [
128
+ {
129
+ type : "VariableDeclarator" ,
130
+ id : {
131
+ type : "Identifier" ,
132
+ name : "CH" ,
133
+ } ,
134
+ init : {
135
+ type : "ObjectExpression" ,
136
+ properties : specifiers . map (
137
+ specifier => ( {
138
+ type : "Property" ,
139
+ method : false ,
140
+ shorthand : true ,
141
+ computed : false ,
142
+ key : {
143
+ type : "Identifier" ,
144
+ name : specifier ,
145
+ } ,
146
+ kind : "init" ,
147
+ value : {
148
+ type : "Identifier" ,
149
+ name : specifier ,
150
+ } ,
151
+ } )
152
+ ) ,
153
+ } ,
154
+ } ,
155
+ ] ,
156
+ kind : "const" ,
157
+ } ,
158
+ specifiers : [ ] ,
159
+ source : null ,
160
+ } ,
161
+ ] ,
162
+ sourceType : "module" ,
163
+ comments : [ ] ,
164
+ } ,
165
+ } ,
166
+ } )
167
+
168
+ tree . children . unshift ( {
169
+ type : "mdxjsEsm" ,
170
+ value : `import { ${ specifiers . join (
171
+ ", "
172
+ ) } } from "@code-hike/mdx/dist/components.cjs.js"`,
173
+ data : {
174
+ estree : {
175
+ type : "Program" ,
176
+ body : [
177
+ {
178
+ type : "ImportDeclaration" ,
179
+
180
+ specifiers : specifiers . map ( specifier => ( {
181
+ type : "ImportSpecifier" ,
182
+ imported : {
183
+ type : "Identifier" ,
184
+ name : specifier ,
185
+ } ,
186
+ local : {
187
+ type : "Identifier" ,
188
+ name : specifier ,
189
+ } ,
190
+ } ) ) ,
191
+ source : {
192
+ type : "Literal" ,
193
+ value :
194
+ "@code-hike/mdx/dist/components.cjs.js" ,
195
+ raw : '"@code-hike/mdx/dist/components.cjs.js"' ,
196
+ } ,
197
+ } ,
198
+ ] ,
199
+ sourceType : "module" ,
200
+ } ,
201
+ } ,
202
+ } )
203
+ }
204
+
110
205
function addImportNode ( tree : SuperNode ) {
111
206
tree . children . unshift ( {
112
207
type : "mdxjsEsm" ,
0 commit comments