在React Native中记录当前目录/文件名

Logging Current Directory/Filename in React Native

本文关键字:当前目录 文件名 记录 React Native      更新时间:2023-09-26

我想知道是否有一种方法可以在React Native中记录当前文件名或目录。类似于NodeJS如何使用__filename__dirname

不,这是不可能的,因为所有的源代码都被捆绑在一个大文件中,然后提供了一个源映射,以便您可以在原始结构中调试它
您可以通过在代码中的某个位置调用以下代码片段来看到这一点:

console.log(new Error().stack);

在常规javascript中,你会得到带有文件和行号的整个跟踪,但在react native中,你得到的是:

Error
at Login (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:83009:9)
at instantiate (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:5712:18)
at new Login (eval at proxyClass (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:5730:16), <anonymous>:4:17)
at ReactCompositeComponentWrapper._constructComponentWithoutOwner (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:22051:19)
at ReactCompositeComponentWrapper._constructComponent (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:22033:13)
at ReactCompositeComponentWrapper.mountComponent (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:21952:15)
at Object.mountComponent (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:20425:29)
at ReactCompositeComponentWrapper.performInitialMount (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:22134:28)
at ReactCompositeComponentWrapper.mountComponent (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:22015:13)
at Object.mountComponent (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:20425:29)"

它显示真实的文件不见了。

您可以将以下babel的插件安装到您的包中:

$ npm i babel-plugin-transform-line
$ npm i babel-plugin-transform-dirname-filename

其中:

  • babel-plugin转换行将__line重写为当前源行号静态值
  • babel-plugin-transform-dirname filename将__filename__dirname重写为当前源文件名和目录

然后将插件添加到您的babel.config.js:中

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: ['babel-plugin-transform-dirname-filename', 'babel-plugin-transform-line']
};

现在您可以使用代码中的变量:

console.log(__filename, __dirname, __line);
// Prints: /Users/user/TestApp/App.js /Users/user/TestApp 62