Configuring for babel.config.js - react-native

I'm relatively new to Expo and React Native. Have been facing problems in using absolute paths while importing the modules. Was reading on how to implement this plugin but I am unable to use it properly since it has only instructions for .babelrc. I did almost everything found on different threads regarding this but still, I am unable to use it properly. In my expo project, I also do not have any .babelrc file instead I have babel.config.js file.
I am trying to convert this code for .babelrc:
{
"presets": ["babel-preset-expo"],
"env": {
"development": {
"plugins": [
"transform-react-jsx-source",
["module-resolver", {
"root": ["./src"]
}]
]
}
}
}
To this for babel.config.js:
module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
};
};
Thanks

Check the configuration:
.babelrc
{
"extends": "./babel.config.js"
}
babel.config.js
module.exports = (api) => {
api.cache(true)
return {
"env": {
"development": {
"plugins": [
"transform-react-jsx-source",
["module-resolver", {
"root": ["./src"]
}]
]
}
},
presets: ['babel-preset-expo']
}
}

Related

Cannot find module or its corresponding type declarations in React Native project

I'm trying to include paths aliases to my project in React Native.
In fact when I start the app it's working so I think my babel.config.js is ok, but in VSCode stills appear an error telling Cannot find module or its corresponding type declarations so I think I'm having my tsconfig.json wrong
babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['.'],
alias: {
'#ali/assets': './src/assets',
'#ali/components': './src/components',
'#ali/colors': './src/theme/colors.ts'
}
}
]
]
}
tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"lib": ["es2017"],
"allowJs": true,
"jsx": "react-native",
"noEmit": true,
"isolatedModules": true,
"strict": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": false,
"rootDir": ".",
"paths": {
"#ali/assets": ["./src/assets/*"],
"#ali/components": ["./src/components/*"],
"#ali/colors": ["./src/theme/colors"]
}
},
"exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"],
"extends": "expo/tsconfig.base"
}
Here's my file
src/screens/Login/index.tsx
import Wellcome from '#ali/components/LogIn/Wellcome'
import React from 'react'
import LoginForm from '../../components/forms/LoginForm'
export const LogIn = () => {
return (
<>
<Wellcome />
<LoginForm />
</>
)
}
export default LogIn
I can see my component Wellcome in my app, but in VSCode stills appear the error.
This is due to a tsconfig.json bad configuration.
You should add baseUrl and remove the starting "." from paths routes.
Try this:
"baseUrl": ".",
"paths": {
"#ali/assets/*": ["src/assets/*"],
"#ali/components/*": ["src/components/*"],
"#ali/colors/*": ["src/theme/colors"]
}

Module not found: Error: Can't resolve '#babylonjs/core/Engines/engine'

I am following a guide to setup a simple BabylonJs example with npm, webpack, typescript and ES6 (https://doc.babylonjs.com/divingDeeper/developWithBjs/npmSupport) and get the following error when running npm run build:
ERROR in ./index.ts 3:17-58
Module not found: Error: Can't resolve '#babylonjs/core/Engines/engine' in 'C:\...\BabylonJSPlayground\HelloWorld'
... same error for other modules in #babylonjs/core
My npm installations:
npm init
npm install --save-dev webpack webpack-cli typescript ts-loader
npm install --save #babylonjs/core #babylonjs/materials #babylonjs/loaders #babylonjs/post-processes #babylonjs/procedural-textures #babylonjs/serializers #babylonjs/gui #babylonjs/inspector
webpack.config.js:
const path = require("path");
module.exports = {
entry: './index.ts',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
extensions: [".ts"]
},
module: {
rules: [
{ test: /\.tsx?$/, loader: "ts-loader" }
]
},
mode: "development",
externals: {
"oimo": true,
"cannon": true,
"earcut": true
},
};
tsconfig.json:
{
"compilerOptions": {
"module": "CommonJS",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"moduleResolution": "Node",
"lib": ["ES6","DOM"],
"target": "ES6",
"types": [
"#babylonjs/core",
"#babylonjs/gui",
"#babylonjs/inspector",
"#babylonjs/loaders",
"#babylonjs/materials",
"#babylonjs/post-processes",
"#babylonjs/procedural-textures",
"#babylonjs/serializers"
],
},
"files": [
"./index.ts"
]
}
The imports in my index.ts (vscode shows now errors of missing modules):
import { Engine } from "#babylonjs/core/Engines/engine";
import { Scene } from "#babylonjs/core/scene";
import { Vector3 } from "#babylonjs/core/Maths/math";
import { HemisphericLight } from "#babylonjs/core/Lights/hemisphericLight";
import { Mesh } from "#babylonjs/core/Meshes/mesh";
import { ArcRotateCamera } from "#babylonjs/core/Cameras/arcRotateCamera";
import { MeshBuilder } from "#babylonjs/core/Meshes/meshBuilder";
The packages where installed with npm successfully under node-modules. Also, vscode did recognize them in the index.ts.
So what is wrong here?

Webpack build fails for IE (11)

Trying to setup webpack to build my .js and .vue files.
Seems to no transpile _name() {} style function to regular JavaScript.
Thought it should do that out of the box, straight into commons js unless otherwise specified.
No idea why, it's crashing only in IE with some generic JS syntax error about semi colon out of place.
I guess some little flag, setting, something, somewhere.
Looking for some suggestions here.
ex vue
<script>
export default {
computed: {
_name() {
return 'blah';
}
}
};
</script>
package.json
"#babel/core": "7.0.0-beta.42",
"#babel/plugin-proposal-object-rest-spread": "7.0.0-beta.42",
"#babel/preset-env": "7.0.0-beta.42",
"babel-loader": "8.0.0-beta.2",
"vue-loader": "9.5.1",
"vue-style-loader": "1.0.0",
"sass-loader": "3.2.3",
"node-sass": "^4.1.1",
"css-loader": "0.25.0",
"style-loader": "0.13.1",
"vue-html-loader": "1.2.3",
"file-loader": "^0.8.4",
"webpack": "3.4.1",
"webpack-dev-server": "1.16.1",
"webpack-stream": "3.2.0",
"copy-webpack-plugin": "3.0.1",
"replace-webpack-plugin": "0.1.2",
"uglifyjs-webpack-plugin": "1.2.7"
config
entry: [__dirname + '/../src/bootstrap.js'],
output: {
path: __dirname + '/../public',
filename: 'app.min.js',
chunkFilename: "[name].[chunkhash:4].js",
publicPath: '/',
},
plugins: [
new CopyWebpackPlugin(
(function () {
var copy = [{
to: '',
from: __dirname + '/../src/core/assets'
}, {
to: '',
from: __dirname + '/../src/app/assets'
}];
if (data.copy) {
copy.concat(data.copy);
}
return copy;
})()
),
new ReplacePlugin({
skip: false,
entry: 'src/index.html',
output: '/public/index.html',
hash: '[hash]',
data: {
scripts: data.scripts
}
})
],
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}, {
test: /\.vue$/,
// exclude: /node_modules/,
loader: 'vue-loader',
options: {
loaders: {
js: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
},
sass: 'sass-loader'
}
}
}]
}
build looks like this
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony default export */ __webpack_exports__["default"] = ({
props: ['name', 'timeout', 'max'],
computed: {
_name() {
return this.name || 'global';
},
...
EDIT:
In the end it was just a matter of adding a few specific transform plugins in the .babelrc file at the root. Probably better way to do this via config. Took a while to match the transforms to each error, but the following set worked for me.
{
"plugins": [
"#babel/plugin-transform-spread",
"#babel/plugin-transform-destructuring",
"#babel/plugin-transform-block-scoping",
"#babel/plugin-transform-arrow-functions",
"#babel/plugin-transform-template-literals",
"#babel/plugin-transform-computed-properties",
"#babel/plugin-transform-shorthand-properties"
]
}
Note: each plugin needs to be installed as a dependency also.
Since it is a custom webpack configuration and it is not clear there is any additional configuration to babel, try to add #babel/plugin-transform-shorthand-properties plugin to babel-loader options for .vue files.
loaders: {
js: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: ['#babel/plugin-transform-shorthand-properties']
}
},
sass: 'sass-loader'
}
from the output it is confirmed that shorthand property is not getting transpiled
you are using the shorthand property of ES6 which is not supported on iE you need to configure the babel config so that it transpiled this into older version ( for more info about browser support visit this link)
to make your babel config compatible for ie use something like this in babelrc
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 versions", "ie >= 11"]
},
"useBuiltIns": true
}],
]
}
if that dosen't work try changing you devtool config in webpack (for example eval to something else ) and check this thread of github

how to get intellisense for methods of modules which are imported from an alias in .vue

In .vue and .js, I can enjoy the intellisense of vscode when developing.
But I found it doesn't work any more when I use an alias.
So I have searched for a while on blogs, found a solution, which is to configure a 'jsconfig.json' as below.
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"allowSyntheticDefaultImports": true,
"baseUrl": "./",
"paths": {
"#/*": [
"src/*"
]
}
}
}
it worked in the .js file but didn't work in .vue file.
Does anyone know how to resolve it ?
Does work in .js
Not work in .vue
With vue-cli the alias is defined in the webpack-config (since #vue/cli uses webpack under the hood). So instead of jsconfig.json (delete it! just do it!) , I would:
1: Install the webpack resolver for eslint:
npm i eslint-import-resolver-webpack
2: Reference the plugin from your .eslintrc.js
"settings": {
"import/resolver": "webpack"
},
Done!
This is my complete .eslintrc.js just to be thorough:
module.exports = {
"settings": {
"import/resolver": "webpack"
},
parserOptions: {
parser: "babel-eslint"
},
extends: [
"eslint:recommended",
"plugin:vue/recommended"
],
"env": {
"browser": true,
"node": true
},
rules: {}
}
If any issues remains I would check the eslint-settings in vscode settings.json:
"eslint.enable": true,
"eslint.provideLintTask": true,
"eslint.workingDirectories": ["src"],
"eslint.validate": ["javascript","javascriptreact","vue"],

How to use import with absolute paths with Expo and React Native?

I'm trying to use absolute import paths instead of relative paths with Expo and React Native.
I looked on the expo docs and couldn't find an answer... Searching for the subject in react community I found babel-plugin-module-resolver but it seems that Expo is already using it so I've changed my .babelrc to create some aliases:
{
"presets": ["babel-preset-expo"],
"env": {
"development": {
"plugins": [
"transform-react-jsx-source",
["module-resolver", {
"root": ["./app"],
"alias": {
"Components": "./app/components",
}
}]
]
}
}
}
But I got the following error:
Unable to resolve module '#expo/vector-icons/glyphmaps/Entypo.json'
from '/Users/eduardoleal/Code/lua/rook/node_modules/#expo/vector-icons/Entypo.js':
Module does not exist in the module map or in these directories: /Users/eduardoleal/Code/lua/rook/node_modules/#expo/vector-icons/node_modules/#expo/vector-icons/glyphmaps , /Users/eduardoleal/Code/lua/rook/node_modules/#expo/vector-icons/glyphmaps This might be related to https://github.com/facebook/react-native/issues/4968 To resolve try the following:
1. Clear watchman watches: 'watchman watch-del-all'.
2. Delete the 'node_modules' folder: 'rm -rf node_modules && npm install'.
3. Reset packager cache: 'rm -fr $TMPDIR/react-*' or 'npm start --reset-cache'.
ABI16_0_0RCTFatal -[ABI16_0_0RCTBatchedBridge stopLoadingWithError:] __34-[ABI16_0_0RCTBatchedBridge start]_block_invoke_2 _dispatch_call_block_and_release _dispatch_client_callout _dispatch_main_queue_callback_4CF __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ __CFRunLoopRun CFRunLoopRunSpecific GSEventRunModal UIApplicationMain main start 0x0
Is there any easy way to import absolute paths?
Update: Expo v32.0.0 and up
Expo init is creating a babel.config.js for you. Just add the plugins key to your babel.config.js file and add your alias. The env key is not needed anymore.
module.exports = function(api) {
api.cache(true)
return {
presets: ['babel-preset-expo'],
plugins: [
[
'module-resolver',
{
alias: {
assets: './assets',
components: './src/components',
modules: './src/modules',
lib: './src/lib',
types: './src/types',
constants: './src/constants',
},
},
],
],
}
}
Update: Changes for Expo.io SDK v20.0.0
Since SDK v20.0.0 you can use the normal Babel Expo presets
{
"presets": ["babel-preset-expo"],
"env": {
"development": {
"plugins": ["transform-react-jsx-source"]
}
},
"plugins": [
["module-resolver", {
"alias": {
"alias-name": "./app",
}
}]
]
}
Expo.io SDK v19.0.0 and before
Without the root-element, separating plugins and changing presets to babel-preset-react-native-stage-0/decorator-support, an alias work for me.
Using Expo.io on Version 16.0.0
Found this in the Expo Forums here: https://forums.expo.io/t/relative-paths-with-expo/654/3
Can you verify that this works on your case too?
{
"presets": ["babel-preset-react-native-stage-0/decorator-support"],
"env": {
"development": {
"plugins": ["transform-react-jsx-source"]
}
},
"plugins": [
["module-resolver", {
"alias": {
"alias-name": "./app",
}
}]
]
}
For latest expo users(sdk version >= 32).
Just add plugins property in your babel.config.js (find this file in project root directory).
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
[
'module-resolver',
{
alias: {
'alias-name': './src/assets/bla/bla',
},
},
],
],
};
};
In adition to Laszlo Schurg's answer in case someone encounters the same problem with Typescript.
If you are using Typescript you also need to add this in your tsconfig
"compilerOptions": {
...
"baseUrl": ".",
"paths": {
"#src/*": ["./src/*"],
"#assets/*": ["./assets/*"]
}
},
That's my config for this babel.config
plugins: [
...
[
"module-resolver",
{
alias: {
"#assets": "./assets",
"#src": "./src",
},
},
],
],
After a while trying to get this working. I could resolve the problem with de following .babelrc:
{
"presets": ["babel-preset-react-native-stage-0/decorator-support"],
"env": {
"development": {
"plugins": ["transform-react-jsx-source"]
}
},
"plugins": [
["module-resolver", {
"alias": {
"react-native-vector-icons": "#expo/vector-icons",
"#expo/vector-icons/lib/create-icon-set": "react-native-vector-icons/lib/create-icon-set",
"#expo/vector-icons/lib/icon-button": "react-native-vector-icons/lib/icon-button",
"#expo/vector-icons/lib/create-icon-set-from-fontello": "react-native-vector-icons/lib/create-icon-set-from-fontello",
"#expo/vector-icons/lib/create-icon-set-from-icomoon": "react-native-vector-icons/lib/create-icon-set-from-icomoon",
"#expo/vector-icons/lib/icon-button": "react-native-vector-icons/lib/icon-button",
"#expo/vector-icons/glyphmaps": "react-native-vector-icons/glyphmaps",
"$components": "./app/components",
"$config": "./app/config",
"$helpers": "./app/helpers",
"$navigators": "./app/navigators",
"$reducers": "./app/reducers",
"$screens": "./app/screens",
"$images": "./assets/images",
"$fonts": "./assets/fonts",
"$icons": "./assets/icons",
"$videos": "./assets/videos",
}
}]
]
}
I copied the content of babel-preset-expo to my .babelrc. It's not the best solution... but it works normally.
More details about it here
./src
|- package.json
|- Bar/
| `- index.js
`- Foo.js
package.json
{
"name": "~" // whatever u want
}
then
import { Foo } from "~/Foo";
import { Bar } from "~/Bar";
// ...
I com with this suggestion:
In your tsconfig.json:
<pre>
<code>
{
"compilerOptions": {
"baseUrl": "./app",
"paths": {
"Components": ["components/*"]
}
},
"include": ["app"]
}
</code>
</pre>
And vite.config.ts resolve might look like this:
<pre>
<code>
resolve: {
alias: {
"Components": "app/components",
}
}
</code>
</pre>
Just simple make you .babelrc simple like this:
{
"presets": ["babel-preset-expo"],
"env": {
"development": {
"plugins": ["transform-react-jsx-source"]
}
}
}
And import like this:
import Entypo from '#expo/vector-icons/Entypo';