使用Babel插件(babel-plugin-module-alias)与React Native

4

我想要使用babel-plugin-module-alias来将React Native项目中的模块路径从../../../../components/foo转换为app/components/foo

我尝试在两个地方独立修改了babel配置,但都没有成功。

首先是在项目根目录下,在index.ios.js旁边:

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

同时,还需要在/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
}

它不会抛出任何错误,只是尝试使用import MyComponent from 'app/components/MyComponent';这样的方式来要求一个模块,但会出现以下错误:

无法解析模块 app/components/MyComponent .... 无效目录 /Users/node_modules/app/components/MyComponent.

我已经尝试清除我所知道的所有缓存:

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

非常感谢任何进一步的想法!

1个回答

6

一个更好的关于上下文的 Github 问题实际上是 https://github.com/tleunen/babel-plugin-module-alias/issues/29。这个问题在 RN 0.24 中已经确认修复。 - Adam Terlson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接