How to use Babel Module Resolver with react-native+expo on publication?
Finally .babelrc works in this format :
{
"presets": ["babel-preset-expo"],
"plugins": [
[
"module-resolver",
{
"root": ["./"],
"alias": {
"@components": "./src/components",
"@screens": "./src/screens",
"@stores": "./src/stores",
"@utils": "./src/utils",
"@services": "./src/services",
"@assets": "./assets",
"@constants": "./src/constants"
}
},
],
],
}
And add '@' when i import :
import stores from '@stores';
If you are like me, still experiencing problems even with @
character in front of your paths,
please, consider using babel-plugin-root-import - an alternative to babel-plugin-module-resolver,
which is not as feature-rich as babel-plugin-module-resolver,
but it is able to solve the essential problem - too many dots in paths like this one
import Button from '../../../../components/Button;
That was the main concern for me.
Here is my config (babel.config.js
):
module.exports = function(api) {
api.cache(true);
const rootImportOpts = {
paths: [
{
root: __dirname,
rootPathPrefix: '~/',
rootPathSuffix: 'src',
},
{
root: __dirname,
rootPathPrefix: '#/',
rootPathSuffix: 'spec',
}
]
};
return {
presets: ['babel-preset-expo'],
plugins: [['babel-plugin-root-import', rootImportOpts]]
};
};
And the folder structure:
expo-app/
...
spec/
src/
...
components/
...
...
app.config.js
babel.config.js
As a result, instead of this:
import Button from '../../../../components/Button;
I use that:
import Button from '~/components/Button;
Also, it works as expected on publication.