Usage of Promise in webpack / react application - reactjs

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

Related

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: [],
},
],
},
},
},
};

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

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

error when trying to load typescript-written package into react storybook project

im working on storybook tests for my react-native project
I decided to use react-native-web to run storybook as a website
Everything is running fine.
Until im trying to run test for some component that uses react-native-inappbrowser-reborn package.
Im getting this error:
As far as i can see - the error is because inappbrowser-reborn uses this syntax:
here is my storybook/main.js file:
module.exports = {
stories: ["../storybook/stories/**/*.stories.js"],
addons: [
"#storybook/addon-actions",
"#storybook/addon-knobs",
"#storybook/addon-docs",
"storybook-addon-rtl",
],
webpackFinal: async (config) => {
config.resolve.alias = {
...(config.resolve.alias || {}),
// Transform all direct `react-native` imports to `react-native-web`
"react-native$": "react-native-web",
// make sure we're rendering output using **web** Storybook not react-native
"#storybook/react-native": "#storybook/react",
// plugin-level react-native-web extensions
"react-native-svg": "react-native-svg/lib/commonjs/ReactNativeSVG.web",
// ...
};
// handle SVG support inside Storybook
const fileLoaderRule = config.module.rules.find((rule) =>
rule.test.test(".svg")
);
fileLoaderRule.exclude = /\.svg$/;
config.module.rules.push({
test: /\.svg$/,
loader: "svg-react-loader",
});
// mutate babel-loader
config.module.rules[0].use[0].options.plugins.push([
"react-native-web",
{ commonjs: true },
//,
]);
return config;
},
};
Please help!

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

Webpack not able to import React component with `<svg`> tag

I have a standard React funtional component which exports a SVG as so;
SomeSVG.js
import React from 'react';
const SomeSVG = props => (
<svg width={24} height={24} {...props}>...</svg>
)
export default SomeSVG;
When using this in Create React App, works fine. Nice inlined SVG where it was expected to be.
Now I'm trying to use this in another project, with a custom webpack setup. But I get the error;
Module parse failed: Unexpected token (4:2)
You may need an appropriate loader to handle this file type.
|
| const SomeSVG = props => (
> <svg width={24} height={24} {...props}>
I imagine I need to have a webpack loader than can support these, my existing webpack settings for JS/JSX/SVG
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
'babel-loader?cacheDirectory=true',
'eslint-loader'
]
},
{
test: /\.svg$/,
loader: 'file-loader',
options: {
name: 'assets_seller/[name].[ext]'
}
},
(I don't think the SVG part is revelant but I'll include it for completeness)
I've tried react-svg-loader as a loader as well with and without options;
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
'babel-loader?cacheDirectory=true',
{
loader: "react-svg-loader",
options: {
jsx: true // true outputs JSX tags
}
},
'eslint-loader'
]
},
But that errors as well
NonErrorEmittedError: (Emitted value instead of an instance of Error) Error in parsing SVG: Non-whitespace before first tag.
My .babelrc config
{
"presets": [
[
"#babel/preset-env", {
"modules": false
}
],
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-transform-modules-commonjs",
"transform-async-to-generator",
"syntax-dynamic-import",
"universal-import",
"#babel/plugin-transform-exponentiation-operator"
]
}
Any ideas would be greatly appriciated.
EDIT: I upgraded Webpack and it's plugins to the latest versions beforehand.
This issue is not related with how babel/webpack handles the SVG but, it's because the (Expo?) webpack config it's not transforming the JSX from the react-svg-main package because of configuration settings (webpack.config.js).
Furthermore, when you add it to the list, the compile process finishes, but the components are not there in runtime because the dependency isn't included and it will never work in this environment (Attempted import error: 'SvgXml' is not exported from react-native-svg).
I will try to update this response & send a pull request to the affected project.
I think I can get this working if I make some changes in the react-svg-main project...
In my case, this is a problem while trying to run an Expo project with web/browser.

Resources