Expo react native not using plugin defined in babel.config.js - reactjs

So I am using minimal workflow with Typescript and I have this in babel.config.js,
module.exports = function (api) {
api.cache(true)
return {
presets: ["babel-preset-expo"],
plugins: [
[
"module-resolver",
{
root: ["."],
alias: {
"lib/": "./"
}
}
]
]
}
}
As you can see I am using babel-plugin-module-resolver to alias path. But it's not working at all. What am I doing wrong here?

I needed to clear cache. yarn ios -- -c

Related

Configuring Vite with styled-jsx

I want to be able to add classes through styled-jsx which can be nested and have tailwind directives(#apply screen etc.). Right now it's working on imported css files.
Here's my Vite config:
import { defineConfig } from "vite";
import react from "#vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react({
babel: {
parserOpts: {
plugins: [
"styled-jsx/babel",
// {
// plugins: ["styled-jsx-plugin-postcss"],
// },
],
},
},
}),
],
});
As you see plugins: ["styled-jsx-plugin-postcss"] is commented, because it results in an error, but it's essential to use postcss settings.
If somebody interested, here's the postcss.config.cjs(for non Vite it's .js):
module.exports = {
plugins: {
'tailwindcss/nesting': 'postcss-nesting',
'postcss-preset-env': {
stage: 1
},
tailwindcss: {},
autoprefixer: {},
}
}
Is there a way to configure it in Vite.js ( in Next.js it's trivial, so if someone wants to suggest this idea, just don't, it's about Vite!)

Allow mjs extension files in React with typescript and craco

I have a basic react app with Craco for tailwindcss support. What I'm trying to do is read from a main.mjs file but when I try to import the file, I run into a ts2307 error that module cannot be found. Is there a way for me to get app to find *.mjs files? Like I have tried going through the craco config documentation but I keep missing the point I guess.
in your craco.config.js file, need to allow tailwind css as well as overwrite webpack configuration as below.
module.exports = {
style: {
postcss: {
plugins: [require('tailwindcss'), require('autoprefixer')],
},
},
webpack: {
configure: {
module: {
rules: [
{
type: 'javascript/auto',
test: /\.mjs$/,
use: [],
},
],
},
},
},
};

Storybook Can't Find Components in React, Next.JS, Typescript Project

I have storybook setup with my next.js, typescript and react project. The project renders fine but storybook breaks and give me the me error: "Module not found: Error: Can't resolve 'components/atoms' in...." It seems like the path to components is causing it to break:
import { Element } from 'components/atoms';
but the following works:
import { Element } from '../../atoms
I have a tsconfig.json file with the following:
"compilerOptions": {
"baseUrl": "src",
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
],
...
I tried some of the suggestions online but none seems to resolve the path issue. I created a webpack.config.js in my .storybook folder with the following, but still get errors.
module.exports = {
...
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules']
}
};
I would like to not use the ../../ when calling files and just be able to use the ./components structure.
Spent some time fighting with Storybook )
Here is my .storybook/main.js version, that finally worked:
const path = require("path");
module.exports = {
webpackFinal: async (config, { configType }) => {
config.resolve.modules.push(path.resolve(__dirname, '../src'));
return config;
},
stories: [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)"
],
addons: [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/preset-create-react-app"
]
}
For someone who is still looking for a solution, try adding the below inside your webpackFinal before returning config. It is because storybook isn't configured to access files using absolute paths.
config.resolve.modules = [...(config.resolve.modules || []), path.resolve('./')]
I was having an issue resolving aliases
Error: Can't resolve '#foo/bar'
In root > .storybook/main.js I added the property config.resolve.alias
const path = require('path');
module.exports = {
stories: ['../libs/feature/src/**/*.stories.#(js|jsx|ts|tsx)'],
addons: [
'#storybook/addon-links',
'#storybook/addon-essentials',
'#storybook/addon-interactions',
],
framework: '#storybook/react',
webpackFinal: async (config, { configType }) => {
config.resolve.alias = {
...config.resolve.alias,
'#foo/bar': path.resolve(__dirname, '../libs/bar/src/'),
};
return config;
},
};
I think what you need is path aliases.
If you're working on a typescript project, you can declare aliases that map to a certain absolute path in your application using tsconfig.json paths compiler option:
"baseUrl": "./src",
"paths": {
"components/*": ["components/*"],
"#/common/*": ["common/*"],
}
Official link => typescriptlang.org
Here you have a good explanation about this typescript feature.
Path aliases with TypeScript in Node.js
Be aware that is not always that easy because in production your build toolchain will have to translate them to the correct paths as tsc doesn’t do it.
Fortunately nexjts has added this feature recently => https://nextjs.org/docs/advanced-features/module-path-aliases

Usage of Promise in webpack / react application

I am trying to use Promise in an react app using webpack but I have this error :
'Promise' is not defined no-undef
So far, everything was working well (used babel to translate js and jsx) but unfortunately Promise does not work.
Furthermore, I have this error in Chrome (latest) and I though Promise was buildin feature.... Am I right ?
Here is a piece of config that I use (I used survivejs kanban app as a starter, I am trying to add some functionalities). I did not change much the initial config :
From web pack.config.js
module: {
loaders: [
{
test: /\.(js|jsx)$/,
// Enable caching for extra performance
loaders: ['babel?cacheDirectory'],
include: include
}
]
}
From .babelrc
{
"presets": [
"es2015",
"react"
],
"env": {
"start": {
"presets": [
"react-hmre"
]
}
}
}
Failing code :
const locales = {
en: () => require('react-intl?locale=en!./en.json'),
fr: () => require('react-intl?locale=fr!./fr.json')
}
function loadLocaleData (locale) {
return new Promise((resolve) => {
locales[locale]()(resolve)
})
}
THE VALID ANSWER IS IN COMMENTS
So far as I know you need te include a Promise polyfill in your webpack config. I use:
plugins: [
new webpack.ProvidePlugin({
'Promise': 'exports?global.Promise!es6-promise'
})
],
Where es6-promise is a npm package which will be include when no promise is available or added by any other npm package

SyntaxError with Jest and React and importing CSS files

I am trying to get my first Jest Test to pass with React and Babel.
I am getting the following error:
SyntaxError: /Users/manueldupont/test/avid-sibelius-publishing-viewer/src/components/TransportButton/TransportButton.less: Unexpected token
> 7 | #import '../variables.css';
| ^
My package.json config for jest look like this:
"babel": {
"presets": [
"es2015",
"react"
],
"plugins": [
"syntax-class-properties",
"transform-class-properties"
]
},
"jest": {
"moduleNameMapper": {
"^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
"^[./a-zA-Z0-9$_-]+\\.png$": "RelativeImageStub"
},
"testPathIgnorePatterns": [
"/node_modules/"
],
"collectCoverage": true,
"verbose": true,
"modulePathIgnorePatterns": [
"rpmbuild"
],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react/",
"<rootDir>/node_modules/react-dom/",
"<rootDir>/node_modules/react-addons-test-utils/",
"<rootDir>/node_modules/fbjs",
"<rootDir>/node_modules/core-js"
]
},
So what am I missing?
moduleNameMapper is the setting that tells Jest how to interpret files with different extension. You need to tell it how to handle Less files.
Create a file like this in your project (you can use a different name or path if you’d like):
config/CSSStub.js
module.exports = {};
This stub is the module we will tell Jest to use instead of CSS or Less files. Then change moduleNameMapper setting and add this line to its object to use it:
'^.+\\.(css|less)$': '<rootDir>/config/CSSStub.js'
Now Jest will treat any CSS or Less file as a module exporting an empty object. You can do something else too—for example, if you use CSS Modules, you can use a Proxy so every import returns the imported property name.
Read more in this guide.
I solved this by using the moduleNameMapper key in the jest configurations in the package.json file
{
"jest":{
"moduleNameMapper":{
"\\.(css|less|sass|scss)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
}
}
}
After this you will need to create the two files as described below
__mocks__/styleMock.js
module.exports = {};
__mocks__/fileMock.js
module.exports = 'test-file-stub';
If you are using CSS Modules then it's better to mock a proxy to enable className lookups.
hence your configurations will change to:
{
"jest":{
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less|scss|sass)$": "identity-obj-proxy"
},
}
}
But you will need to install identity-obj-proxy package as a dev dependancy i.e.
yarn add identity-obj-proxy -D
For more information. You can refer to the jest docs
UPDATE who use create-react-app from feb 2018.
You cannot override the moduleNameMapper in package.json but in jest.config.js it works, unfortunately i havent found any docs about this why it does.
So my jest.config.js look like this:
module.exports = {
...,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(scss|sass|css)$": "identity-obj-proxy"
}
}
and it skips scss files and #import quite well.
Backing my answer i followed jest webpack
Similar situation, installing identity-object-proxy and adding it to my jest config for CSS is what worked for me.
//jest.config.js
module.exports = {
moduleNameMapper: {
"\\.(css|sass)$": "identity-obj-proxy",
},
};
The specific error I was seeing:
Jest encountered an unexpected token
/Users/foo/projects/crepl/components/atoms/button/styles.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.button { }
^
SyntaxError: Unexpected token .
1 | import React from 'react';
> 2 | import styles from './styles.css';
If you're using ts-jest, none of the solutions above will work! You'll need to mock transform.
jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
roots: [
"<rootDir>/src"
],
transform: {
".(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/jest-config/file-mock.js",
'.(css|less)$': '<rootDir>/jest-config/style-mock.js'
},
};
file-mock.js
module.exports = {
process() {
return `module.exports = 'test-file-stub'`;
},
};
style-mock.js
module.exports = {
process() {
return 'module.exports = {};';
}
};
I found this working example if you want more details.
Solution of #import Unexpected token=:)
Install package:
npm i --save-dev identity-obj-proxy
Add in jest.config.js
module.exports = {
"moduleNameMapper": {
"\\.(css|less|scss)$": "identity-obj-proxy"
}
}
Update: Aug 2021
If you are using Next JS with TypeScript. Simply follow the examples repo.
Else you will be wasting days configuring the environment.
https://github.com/vercel/next.js/tree/canary/examples/with-jest
I added moduleNameMapper at the bottom of my package.json where I configured my jest just like this:
"jest": {
"verbose": true,
"moduleNameMapper": {
"\\.(scss|less)$": "<rootDir>/config/CSSStub.js"
}
}

Resources