React Native tsconfig Base URL is not working - reactjs

Why base url and paths work on normal React but not on React Native??
This is my tsconfig file:
{
"compilerOptions": {
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"baseUrl": ".",
"paths": {
"components/*": ["./components/*"],
"assets/*": ["./assets/*"],
"screens/*": ["./screens/*"],
"navigation/*": ["./navigation/*"],
"api/*": ["./api/*"],
"utils/*": ["./utils/*"],
"#shared/*": [
"../shared/*"
]
}
},
"include": [
"./*"
],
"extends": "expo/tsconfig.base"
}
From App.tsx I tried to import AppNav component from "navigation/AppNav" but it gives error that "Unable to resolve module navigation/AppNav"
I even tried to install modeule-resolver plugin for babel but it didnt work:
module.exports = function(api) {
api.cache(false);
return {
presets: ['babel-preset-expo'],
plugins: [
"nativewind/babel",
[
"module-resolver",
{
"root": ["./"],
"alias": {
"components/*": "components/*",
"assets/*": "assets/*",
"screens/*": "screens/*",
"navigation/*": "navigation/*",
"api/*": "api/*",
"utils/*": "utils/*",
}
}
]
],
};
};
I tried with regex expression but still didnt work
module.exports = function(api) {
api.cache(false);
return {
presets: ['babel-preset-expo', "module:metro-react-native-babel-preset"],
plugins: [
"nativewind/babel",
[
"module-resolver",
{
"root": ["."],
"alias": {
"components/(.+)": "./components/\\1",
"assets/(.+)": "./assets/*",
"screens/(.+)": "./screens/*",
"navigation/(.+)": "./navigation/\\1",
"api/(.+)": "./api/*",
"utils/(.+)": "./utils/*",
}
}
]
],
};
};

Related

Migrating NextJS#11 to NextJS#12 with SWC config

I'm trying to migrate my NextJS App to version 12.
it's working properly using babel config, but I like to change the environment to swc.
I have the error below during production build:
./src/pages/_app.tsx Module not found: Can't resolve
'#styles/index.scss' in
'/project/src/pages'
these are my config files:
tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"baseUrl": ".",
"paths": {
"#assets/*": ["src/assets/*"],
"#api": ["src/api"],
"#i18n": ["src/scripts/i18n"],
"#styles": ["./src/styles"],
"#redux": ["./src/redux"],
"#slices/*": ["./src/redux/slices/*"],
"#utils": ["./src/utils"],
"#root/*": ["./src/root/*"],
"#hooks/*": ["./src/hooks/*"],
"#schema/*": ["./src/types/schema/*"],
"#configs": ["./src/app.config"],
"#contexts/*": ["./src/contexts/*"],
"#components/*": ["./src/components/*"],
"#extensions/*": ["./src/scripts/extensions/*"],
"~menu/*": ["./src/sections/menu/*"],
"~order/*": ["./src/sections/order/*"],
"~search/*": ["./src/sections/search/*"],
"~growth/*": ["./src/sections/growth/*"],
"~army/*": ["./src/sections/army/*"],
"#jest-provider": ["./src/root/JestProvider"],
"~service/*": ["./src/service/*"]
}
},
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.test.js"]
}
next.config.js
const webpack = require('webpack')
const withPWA = require('next-pwa')
const pJson = require('./package.json')
const withPlugins = require('next-compose-plugins')
const setupENVs = require('./src/scripts/env.config')
const bundleAnalyzer = require('#next/bundle-analyzer')
const routesConfig = require('./src/scripts/routes.config')
const runtimeCaching = require('./src/scripts/sw.cache.config')
const {withSentryConfig} = require('#sentry/nextjs')
// const withTM = require('next-transpile-modules')(['design-system'])
const isDev = process.env.NODE_ENV !== 'production'
routesConfig(isDev)
const plugins = [new webpack.DefinePlugin(setupENVs())]
const securityHeaders = [
{
key: 'X-Frame-Options',
value: 'SAMEORIGIN',
},
]
const basConfig = (nextConfig = {}) => ({
...nextConfig,
webpack(config, options) {
config.plugins.push(...plugins)
if (typeof nextConfig.webpack === 'function') {
return nextConfig.webpack(config, options)
}
return config
},
})
const withAnalyzer = bundleAnalyzer({
enabled: process.env.ANALYZE === 'true',
})
let transpileModules
if (isDev) {
transpileModules = basConfig()
} else if (process.env.ANALYZE === 'true') {
transpileModules = basConfig(withAnalyzer())
} else {
transpileModules = basConfig(
withPWA({pwa: {dest: 'public', runtimeCaching, disable: true}})
)
}
const moduleExports = withPlugins([transpileModules], {
compiler: {
styledComponents: {
displayName: true,
ssr: true,
},
removeConsole: true,
// reactRemoveProperties: true,
},
env: {
APP_VERSION: pJson.version,
},
async headers() {
return [
{
source: '/(.*)',
headers: securityHeaders,
},
]
},
sentry: {
disableClientWebpackPlugin: true,
disableServerWebpackPlugin: true,
},
swcMinify: true,
experimental: {
forceSwcTransforms: true,
swcTraceProfiling: true,
swcMinifyDebugOptions: {
compress: {
defaults: true,
side_effects: false,
},
},
modularizeImports: {
lodash: {
transform: 'lodash/{{member}}',
},
},
},
})
module.exports = withSentryConfig(moduleExports)
babel.config.json
{
"presets": [
[
"next/babel",
{
"preset-env": {}
}
]
],
"plugins": [
["styled-components", {"ssr": true, "displayName": true}],
[
"module-resolver",
{
"root": "./src",
"alias": {
"#assets": "./src/assets",
"#api": "./src/api",
"#i18n": "./src/scripts/i18n",
"#root": "./src/root",
"#styles": "./src/styles",
"#redux": "./src/redux",
"#slices": "./src/redux/slices",
"#hooks": "./src/hooks",
"#utils": "./src/utils",
"#schema": "./src/types/schema",
"#contexts": "./src/contexts",
"#configs": "./src/app.config",
"#components": "./src/components",
"#extensions": "./src/scripts/extensions",
"~menu": "./src/sections/menu",
"~order": "./src/sections/order",
"~search": "./src/sections/search",
"~growth": "./src/sections/growth",
"~army": "./src/sections/army",
"#jest-provider": "./src/root/JestProvider",
"#mockData": "./__mocks__/data",
"~service": "./src/service"
},
"extensions": [".js", ".jsx", ".ts", ".tsx", ".es", ".es6", ".mjs"]
}
]
],
"env": {
"production": {
"plugins": [["transform-remove-console"]]
},
"test": {
"presets": [["#babel/preset-env", {"modules": false}], "next/babel"]
}
}
}
could you please help me on this?
You should consider these two things.
First, as the next.js document says you're opting out the swc compiler by having babel config.
The new Rust compiler is backwards compatible. If you have an existing Babel configuration, you will automatically be opted out.
here's the document: https://nextjs.org/blog/next-12#faster-builds-and-fast-refresh-with-rust-compiler
Second, you have some issues with your module mapping as the styles must not be under the 'pages' folder.
'/project/src/pages'

How to declare and use a local component as module?

I export const FontXLarge = 18; in ThemeFont.ts.
When I want to use it, I used to use import {FontXLarge} from '../theme/ThemeFont';
After I add
{
"name": "theme"
}
I can use import {FontXLarge} from 'theme/ThemeFont'; but I can't link to the folder.
So I think that if I declare module 'ThemeFont' I can link it. And the fact that I did it. When I ctrl + click (or alt + click in VSCode, depending on your setting), it can open the file ThemeFont.ts when I use import {FontXLarge} from 'ThemeFont';
declare module 'ThemeFont' {
export const FontXLarge = 18;
}
When hover, it will show like that
But it shows error when build: Unable to resolve module ThemeFont in node_modules
We can use this library to declare local component https://github.com/tleunen/babel-plugin-module-resolver
My config for it:
create/edit: tsconfig.json
{
"compilerOptions": {
"skipLibCheck": true,
"allowJs": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react",
"lib": ["es6"],
"moduleResolution": "node",
"noEmit": true,
"strict": true,
"target": "esnext",
"baseUrl": "./app",
"paths": {
"#/*": ["./*"]
},
"outDir": "../dst/",
"typeRoots": ["node_modules/#types"]
},
"lib": ["es2016"],
"exclude": [
"node_modules",
"babel.config.js",
"metro.config.js",
"jest.config.js"
]
}
create/edit jsconfig.json
{
"compilerOptions": {
"paths": {
"#/*": [
"./app/*"
]
}
}
}
create/edit jsconfig.js
System.config({
paths: {
'#/*': './app/*',
},
})
edit babel.config.js
const presets = ['module:metro-react-native-babel-preset'];
const plugins = [
[
'react-native-reanimated/plugin',
// {
// globals: ['__scanQRCodes', '__decode'],
// },
],
[
'module-resolver',
{
root: ['./app'],
extensions: ['.js', '.json'],
alias: {
'#': './app',
},
},
],
];
const env = {
production: {
plugins: ['react-native-paper/babel'],
},
};
module.exports = {
presets,
plugins,
env,
};
Now you can use
import {FontXLarge} from '#/Theme/ThemeFont';
remember that after config it, resetting app cache:
yarn start --reset-cache

Background classes and custom theme don't work in Tailwind CSS with React

I am currently working on a project with ReactJS, Typescript and TailwindCSS and everything seems to be working properly. The point is, all TailwindCSS classes work just fine except the ones for the background. Whenever I use a class like,bg-sky-500 or bg-slate-500, the color never displays and the background remains as it is. Also, I have tried to set a custom theme inside tailwindcss.config.json, but it didn't work either. Here are the configs used in the project:
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"baseUrl": "src",
"noImplicitAny": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": ["src"]
}
tailwind.config.ts
module.exports = {
content: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
purge: [],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
postcss.config.ts
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
main.ts
const path = require("path");
module.exports = {
stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.#(js|jsx|ts|tsx)"],
addons: [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/addon-interactions",
"#storybook/preset-create-react-app",
],
framework: "#storybook/react",
core: {
builder: "#storybook/builder-webpack5",
},
webpackFinal: async (config) => {
config.module.rules.push({
test: /\,css&/,
use: [
{
loader: "postcss-loader",
options: {
ident: "postcss",
plugins: [require("tailwindcss"), require("autoprefixer")],
},
},
],
include: path.resolve(__dirname, "../"),
});
return config;
},
};
preview.ts
import "index.css";
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
index.css
#tailwind base;
#tailwind components;
#tailwind utilities;
#tailwind forms;
Would anyone be able to help with this?
The "sky" and "slate" colors only became available in Tailwind CSS version 3+. I would recommend upgrading to the latest for these colors and the many additional improvements.
If you are stuck with v2, you should reference the list of colors in the old documentation: https://v2.tailwindcss.com/docs/background-color
Alternatively, you can add these colors in your tailwind.config.js file in the theme section, copying the values from Tailwind 3+:
module.exports = {
theme: {
extend: {
colors: {
slate: {
50: "rgb(248 250 252)",
100: "rgb(241 245 249)",
...
},
sky: {
50: "rgb(240 249 255)",
100: "rgb(224 242 254)",
...
},
},
},
},
}
See: https://v2.tailwindcss.com/docs/customizing-colors

Trying to render a JSX component inside TSX makes TS interpret the JSX component's arguments as string

I'm migrating certain parts of the codebase to TS and I have an original JSX component Icon that's defined as follows:
export const Icon = ({ width, height}) => {
return(<div></div>);
};
Inside my Dropdown.tsx, I'm using it as such:
import { Icon } from './Icon';
type Props = {
id: string,
props?: object
}
export const Dropdown = ({id, ...props}: Props): JSX.Element => {
return <Icon />;
}
However, TS screams at me with TS2322: Type '{}' is not assignable to type 'string'. when I'm trying to render Icon. I can get it to render if I just do Icon('') which solves the issue TS is telling me about, but, obviously, I can't pass any arguments to the component. Why can't a TSX component work with a JSX component?
The code, as I provided it, should work: https://codesandbox.io/s/fervent-matan-igjrp?file=/src/Dropdown.tsx - it's just something on my end that I can't figure out.
Here's my setup:
webpack.js:
module: {
rules: [
{
test: /\.(ts|tsx)?$/,
use: {
loader: 'ts-loader',
},
exclude: /node_modules/,
},
{
test: /\.(js|jsx)?$/,
exclude: /[\\/]node_modules[\\/]/,
use: 'babel-loader',
},
]
}
tsconfig.json:
{
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"strict": true,
"sourceMap": true,
"moduleResolution": "node",
"noImplicitAny": true,
"noEmitOnError": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"allowJs": true,
"checkJs": false,
"target": "ESnext",
"module": "esnext",
"declaration": true,
"jsx": "react",
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"plugins": [
{
"name": "typescript-plugin-css-modules"
}
]
},
"baseUrl": ".",
"paths": {
"REDACTED": ["src/index.js"]
},
"include": ["./src/**/*.ts", "./src/**/*.tsx"],
"exclude": ["./out.d.ts", "node_modules", "dist", "src/**/*.js", "src/**/*.jsx"]
}

Typescript replaces JSX in a .tsx file with undefined

This is a confusing bug, I'm coming back to frontend work after a hiatus of over an year.
Setup and configuration
I am experimenting with rollup and react-runkit to create some docs for my backend typescript project.
Typescript config
{
"compilerOptions": {
"allowUnreachableCode": false,
"alwaysStrict": true,
"declaration": false,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"lib": ["dom", "esnext"],
"jsx": "react",
"module": "commonjs",
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"noImplicitThis": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"sourceMap": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"strictPropertyInitialization": true,
"target": "es5"
},
"include": ["src/docs", "typings"],
"exclude": ["node_modules"]
}
Rollup config
import typescript from '#rollup/plugin-typescript';
import resolve from '#rollup/plugin-node-resolve';
import replace from '#rollup/plugin-replace';
export default {
input: 'src/docs/index.tsx',
output: [
{
file: 'src/docs/dist/bundle.js',
format: 'umd'
}
],
plugins: [
typescript({
tsconfig: './tsconfig.docs.json'
}),
resolve(),
replace({
'process.env.NODE_ENV': JSON.stringify('development')
})
]
}
The React module in question
import * as React from 'react';
import * as ReactDom from 'react-dom';
import * as Embed from 'react-runkit';
function App() {
const source = `console.log('Hello World');`;
return (
<div>
<Embed source={source} />
</div>
);
}
console.log('Hello, World');
const app = document.getElementById('app');
ReactDom.render(<App />, app);
READ THIS (THE ERROR, THE CONCERNING PART) in the bundled output:
function App() {
var source = "console.log('Hello World');";
return (undefined("div", null,
undefined(Embed, { source: source })));
}
console.log('Hello, World');
var app = document.getElementById('app');
undefined(undefined(App, null), app);
After a bit of digging, I find that when I include:
Option 1: Includes the React Source but not the JSX transform:
plugins: [
resolve(),
replace({
'process.env.NODE_ENV': JSON.stringify('development')
}),
commonjs(),
typescript({
jsx: 'react',
}),
]
gives me the react source in the bundle.js but leaves the <div> as undefined.
Option 2: Includes the React transform but not the react source:
plugins: [
resolve(),
replace({
'process.env.NODE_ENV': JSON.stringify('development')
}),
commonjs(),
typescript({
jsx: 'react',
module: 'CommonJS'
}),
]

Resources