11const path = require ( 'path' ) ;
2+ const { existsSync} = require ( 'fs' ) ;
23// 用于匹配 import { Button } from 'antd';
34const importReg = / i m p o r t \s + { \s * ( .+ ) \s * } \s + f r o m \s + [ ' " ] ( .+ ) [ ' " ] / g;
45
@@ -12,12 +13,21 @@ function tranCamel2(componentName, joinString) {
1213 return componentName . replace ( / ( [ a - z ] ) ( [ A - Z ] ) / g, `$1${ joinString } $2` ) . toLowerCase ( ) ;
1314}
1415
16+ /**
17+ * file exists in node_modules?
18+ * @param filePath
19+ */
20+ function fileExistInNpm ( filePath ) {
21+ return existsSync ( path . resolve ( __dirname , '../../' , filePath ) ) ;
22+ }
23+
1524function replaceImport ( source , options = { } ) {
1625 const {
1726 lib, // lib name
1827 libDir = 'lib' , //lib dir in npm
1928 style, // style file path
2029 camel2, // translate ComponentName to component-name | component_name
30+ existCheck = fileExistInNpm , // only import file when exits
2131 } = options ;
2232 if ( ! lib ) {
2333 return source ;
@@ -34,10 +44,18 @@ function replaceImport(source, options = {}) {
3444 }
3545
3646 if ( componentName . length > 0 ) {
37- ret += `import ${ componentName } from '${ path . join ( importFrom , libDir , componentPath ) } '\n` ;
47+ // import js file
48+ const jsFilePath = path . join ( importFrom , libDir , componentPath ) ;
49+ if ( typeof existCheck !== 'function' || existCheck ( jsFilePath ) ) {
50+ ret += `import ${ componentName } from '${ jsFilePath } '\n` ;
51+ }
3852
3953 if ( style ) {
40- ret += `import '${ path . join ( importFrom , libDir , componentPath , style ) } '\n` ;
54+ // import style file
55+ const styleFilePath = path . join ( importFrom , libDir , componentPath , style ) ;
56+ if ( typeof existCheck !== 'function' || existCheck ( styleFilePath ) ) {
57+ ret += `import '${ styleFilePath } '\n` ;
58+ }
4159 }
4260 }
4361 } ) ;
0 commit comments