11// Most of this code was taken from @satya 164's babel-plugin-css-prop
22// @see https://github.com/satya164/babel-plugin-css-prop
33import { addDefault } from '@babel/helper-module-imports'
4+ import { importLocalName } from '../utils/detectors'
45import { useCssProp } from '../utils/options'
56
67const getName = ( node , t ) => {
@@ -9,9 +10,7 @@ const getName = (node, t) => {
910 return `${ getName ( node . object , t ) } .${ node . property . name } `
1011 }
1112 throw path . buildCodeFrameError (
12- `Cannot infer name from node with type "${
13- node . type
14- } ". Please submit an issue at github.com/styled-components/babel-plugin-styled-components with your code so we can take a look at your use case!`
13+ `Cannot infer name from node with type "${ node . type } ". Please submit an issue at github.com/styled-components/babel-plugin-styled-components with your code so we can take a look at your use case!`
1514 )
1615}
1716
@@ -20,27 +19,36 @@ export default t => (path, state) => {
2019 if ( path . node . name . name !== 'css' ) return
2120
2221 const program = state . file . path
22+
2323 // state.customImportName is passed through from styled-components/macro if it's used
2424 // since the macro also inserts the import
25- let importName = state . customImportName
26- // Insert import if it doesn't exist yet
25+ let importName =
26+ state . customImportName || t . identifier ( importLocalName ( 'default' , state ) )
27+
2728 const { bindings } = program . scope
28- if ( ! importName || ! bindings [ importName . name ] ) {
29- importName = addDefault ( path , 'styled-components' , {
30- nameHint : importName ? importName . name : 'styled' ,
29+
30+ // Insert import if it doesn't exist yet
31+ if ( ! bindings [ importName . name ] ) {
32+ addDefault ( path , 'styled-components' , {
33+ nameHint : 'styled' ,
3134 } )
35+
36+ importName = t . identifier ( importLocalName ( 'default' , state , true ) )
3237 }
33- if ( ! state . customImportName ) state . customImportName = importName
3438
3539 const elem = path . parentPath
3640 const name = getName ( elem . node . name , t )
3741 const id = path . scope . generateUidIdentifier (
3842 'Styled' + name . replace ( / ^ ( [ a - z ] ) / , ( match , p1 ) => p1 . toUpperCase ( ) )
3943 )
4044
41- const styled = t . callExpression ( importName , [
42- / ^ [ a - z ] / . test ( name ) ? t . stringLiteral ( name ) : t . identifier ( name ) ,
43- ] )
45+ let styled
46+
47+ if ( / ^ [ a - z ] / . test ( name ) ) {
48+ styled = t . memberExpression ( importName , t . identifier ( name ) )
49+ } else {
50+ styled = t . callExpression ( importName , [ t . identifier ( name ) ] )
51+ }
4452
4553 let css
4654
0 commit comments