简体   繁体   中英

Babel plugin (babel-plugin-module-alias) with React Native

I am wanting to use babel-plugin-module-alias for transforming module paths from ../../../../components/foo into app/components/foo in my React Native project.

I have attempted to modify the babel config in two places independently, neither works.

One, at the root of my project next to the index.ios.js :

{
  "plugins": [
    ["babel-plugin-module-alias", [
      { "src": "./app", "expose": "app" }
    ]]
  ]
}

And two, at /node_modules/react-native/packager/react-packager/.babelrc :

{
  "retainLines": true,
  "compact": true,
  "comments": false,
  "plugins": [
    ["babel-plugin-module-alias", [
      { "src": "./app", "expose": "app" }
    ]],
    "syntax-async-functions",
    "syntax-class-properties",
    "syntax-trailing-function-commas",
    "transform-class-properties",
    "transform-es2015-arrow-functions",
    "transform-es2015-block-scoping",
    "transform-es2015-classes",
    "transform-es2015-computed-properties",
    "transform-es2015-constants",
    "transform-es2015-destructuring",
    ["transform-es2015-modules-commonjs", {"strict": false, "allowTopLevelThis": true}],
    "transform-es2015-parameters",
    "transform-es2015-shorthand-properties",
    "transform-es2015-spread",
    "transform-es2015-template-literals",
    "transform-flow-strip-types",
    "transform-object-assign",
    "transform-object-rest-spread",
    "transform-react-display-name",
    "transform-react-jsx",
    "transform-regenerator",
    "transform-es2015-for-of"
  ],
  "sourceMaps": false
}

It doesn't throw any errors, simply trying to require a module as such import MyComponent from 'app/components/MyComponent'; yields the error:

Unable to resolve module app/components/MyComponent from .... Invalid directory /Users/node_modules/app/components/MyComponent .

I have tried nuking every cache I'm aware of:

watchman watch-del-all
rm -rf $TMPDIR/react-*
./node_modules/react-native/packager/packager.sh start --resetCache

Any further ideas would be greatly appreciated!

After upgrading npm/node/react-native/react to its latest:

react-native: ^0.29.0
react: 15.2.1
npm: 3.10.3
node: 6.3.0

Then:

watchman watch-del-all
npm start -- --reset-cache

This issue went away.

You can check more about this issue here: https://github.com/facebook/react-native/issues/4968 and https://github.com/tleunen/babel-plugin-module-alias/issues/29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM