I'm trying a tutorial for a basic react web app and it works perfectly in chrome. Here is my code:
import React, {Component} from 'react';
export default class App extends Component {
async componentDidMount() {
const [r1,r2] = await Promise.all([
fetch('http://api.mywebsite.com/content/cars'),
fetch('http://api.mywebsite.com/content/aircrafts'),
]);
this.setState({content:await r1.json(),content2: await r2.json()});
}
render() {
if(this.state) {
console.log(this.state);
}
return (
<div>hello</div>
)
}
}
This works exactly as I expect in Chrome - load up the react component, fetch some data, set the state, and print the state to console.
However, this code will not run in Internet Explorer 11. All I get is a blank page, and in my developer tools, I get the error
Expected '}'
When I click on the link to the error, it highlights this segment of code:
_createClass(App, [{
key: 'componentDidMount',
value: async function componentDidMount() {
var _ref = await Promise.all([fetch('http://new.evermight.com/content/index'), fetch('http://new.evermight.com/content/index')]),
_ref2 = _slicedToArray(_ref, 2),
With an arrow pointing to the line value: async function componentDidMount() {.
How do I make this work in Internet Explorer 11? I only want setState to fire after the fetch calls and such are complete. I need the await behaviour.
EDIT
I am using webpack to compile my project. And if it helps, here is my package.json file:
{
"name": "scroll",
"version": "0.1.0",
"private": true,
"dependencies": {
"animated": "^0.2.1",
"es2015": "0.0.0",
"gsap": "^1.20.3",
"history": "^4.7.2",
"jquery": "^3.2.1",
"react": "^16.1.1",
"react-dom": "^16.1.1",
"react-ga": "^2.4.1",
"react-router-dom": "^4.2.2",
"react-scripts": "0.9.5",
"react-transition-group": "^1.2.0",
"scrollmagic": "^2.0.5",
"video-element": "^1.0.3"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^0.1.17",
"css-loader": "^0.25.0",
"eslint": "^4.13.0",
"eslint-config-aqua": "^2.0.1",
"eslint-plugin-react": "^7.5.1",
"file-loader": "^0.9.0",
"node-sass": "^3.10.1",
"sass-loader": "^4.0.2",
"style-loader": "^0.13.1",
"uglifyjs-webpack-plugin": "^1.1.6",
"url-loader": "^0.5.7",
"webpack": "^3.8.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
And here is my webpack.config.js
var webpack = require('webpack');
var CleanPlugin = require('clean-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: {app:'./src/Index.js'},
output: {
filename: '[name].bundle.js',
chunkFilename: '[id].[hash].bundle.js',
path: '/var/www/html/public/build',
publicPath: '/build/'
},
plugins: [
// This plugin minifies all the Javascript code of the final bundle
new UglifyJsPlugin({
uglifyOptions:{
mangle: true,
compress: {
warnings: false, // Suppress uglification warnings
},
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'main', // Move dependencies to our main file
children: true, // Look for common dependencies in all children,
minChunks: 2, // How many times a dependency must come up before being extracted
})
],
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' },
{ test: /\.scss$/, loaders: [ 'style-loader', 'css-loader', 'sass-loader' ]},
{ test: /\.(jpg|gif|png|otf|eot|woff|svg|ttf)(\?.*)?$/, loader: "file-loader" }
]
}
}
Actually, I did get async and await to work in IE11. In my question, I also had a problem with fetch not being supported in IE11. Here's what I did to solve both problems. I went to my bash terminal and typed this
npm install --save es6-promise
npm install --save-dev babel-polyfill
npm install --save-dev babel-plugin-transform-async-to-generator
npm install --save isomorphic-fetch
Next, I added these two lines to the very beginning of my src/Index.js before any other code because it is my entry point:
import "babel-polyfill";
import "isomorphic-fetch";
Then I ran the webpack command, and now my IE11 supports the code I created with async await and it supports the fetch command.
async-await is not supported in IE.
Check the MDN docs
You need to use Promises instead like
componentDidMount() {
Promise.all([
fetch('http://api.mywebsite.com/content/cars'),
fetch('http://api.mywebsite.com/content/aircrafts'),
]).then(([r1, r2]) => {
this.setState({content:r1.json(),content2: r2.json()});
})
}
Also in order to support promises in IE, you need to use a 3rd party Polyfill libraries like BlueBird or use babel-polyfill
Related
I'm trying to use devextreme datagrid in my spfx application and I'm not able to load the webpack handler. Please point me in the right direction. I've tried different variations on how to include the handlers in module.export by following guidance from previous stack overflow questions but none of them helped.
Below is my gulpfile.js file:
'use strict';
const build = require('#microsoft/sp-build-web');
//const path = require('path');
module.exports = {
module: {
rules:[
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(woff|woff2|ttf|eot)$/,
use: 'file-loader?name=fonts/[name].[ext]!static'
}
]
}
}
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
var result = getTasks.call(build.rig);
result.set('serve', result.get('serve-deprecated'));
return result;
};
build.initialize(require('gulp'));
build.tslintCmd.enabled = false;
I've installed css-loader, style-loader, url-loader and file-loader. Below is my package.json
{
"name": "search-based-list-view-webpart",
"version": "0.0.2",
"private": true,
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"#devexpress/dx-react-core": "^3.0.4",
"#devexpress/dx-react-grid": "^3.0.4",
"#devexpress/dx-react-grid-material-ui": "^3.0.4",
"#emotion/react": "^11.9.3",
"#emotion/styled": "^11.9.3",
"#microsoft/rush-stack-compiler-4.2": "^0.1.2",
"#microsoft/sp-core-library": "1.14.0",
"#microsoft/sp-lodash-subset": "1.14.0",
"#microsoft/sp-office-ui-fabric-core": "1.14.0",
"#microsoft/sp-property-pane": "1.14.0",
"#microsoft/sp-webpart-base": "1.14.0",
"#mui/material": "^5.9.0",
"#pnp/graph": "^3.4.1",
"#pnp/sp": "^3.4.1",
"#pnp/spfx-controls-react": "3.8.1",
"devextreme": "22.1.3",
"devextreme-react": "22.1.3",
"office-ui-fabric-react": "7.174.1",
"react": "16.13.1",
"react-dom": "16.13.1"
},
"devDependencies": {
"#microsoft/rush-stack-compiler-3.9": "0.4.47",
"#microsoft/sp-build-web": "1.14.0",
"#microsoft/sp-module-interfaces": "1.14.0",
"#microsoft/sp-tslint-rules": "1.14.0",
"#types/react": "16.9.51",
"#types/react-dom": "16.9.8",
"#types/webpack-env": "1.13.1",
"ajv": "~5.2.2",
"css-loader": "^6.7.1",
"file-loader": "^6.2.0",
"gulp": "~4.0.2",
"style-loader": "^3.3.1",
"url-loader": "^4.1.1"
}
}
In the .tsx file, I'm trying to import the css file as shown below:
import 'devextreme/dist/css/dx.light.css';
No matter what I try, I get the following error when I try to do gulp serve
Error - [webpack] 'dist':
./node_modules/devextreme/dist/css/icons/dxicons.woff2 1:4
Module parse failed: Unexpected character ' ' (1:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
# ./node_modules/devextreme/dist/css/dx.light.css (./node_modules/#microsoft/spfx-heft-plugins/node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/src??postcss!./node_modules/devextreme/dist/css/dx.light.css) 4:38-70
# ./node_modules/devextreme/dist/css/dx.light.css
# ./lib/webparts/searchBasedListViewWebpart/components/SearchBasedListViewWebpart.js
# ./lib/webparts/searchBasedListViewWebpart/SearchBasedListViewWebpartWebPart.js
I had the same issue.
Just extend your gulpfile.js with this:
...
// Font loader configuration for webfonts
const fontLoaderConfig = {
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}]
};
// Merge custom loader to web pack configuration
build.configureWebpack.mergeConfig({
additionalConfiguration: (generatedConfiguration) => {
generatedConfiguration.module.rules.push(fontLoaderConfig);
return generatedConfiguration;
}
});
...
Link to solution:
woff2 files for fonts not supported
How to bundle and use custom web fonts in SPFx projects
Community, just started with React and I've created the simplest stuff ever. Does it work? Of course... not.
I've been googling and tried to make those adjustments described. But still, my killer application won't run and I seem to end up with two different error messages depending on the actions i take:
"Babel Plugin/Preset files are not allowed to export objects, only functions"
"Uncaught ReferenceError: process is not defined"
I honestly don't know how to proceed, I've tried to upgrade to the latest "#babel/...", tried to downgrade to earlier babel versions, but React is playing hide and seek with me.
// app.js
import React from 'react';
import ReactDOM from 'react-dom';
const text = <p>Hello world</p>
ReactDOM.render(text, document.getElementById('app'));
// babel.rc
{
"presets": [
"env",
"react"
]
}
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
mode: 'none',
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}]
}
};
// package.json
{
"name": "killer-app",
"version": "1.0.0",
"main": "index.js",
"author": "",
"license": "",
"scripts": {
"serve": "live-server public/",
"build": "webpack --watch",
"build-babel": "babel src/app.js --out-file=public/scripts/app.js --presets=env,react --watch"
},
"dependencies": {
"babel-cli": "^6.26.0",
"babel-core": "6.25.0",
"babel-loader": "7.1.1",
"babel-preset-env": "1.5.2",
"babel-preset-react": "6.24.1",
"live-server": "^1.2.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"validator": "^13.7.0",
"webpack": "^5.73.0"
},
"devDependencies": {
"webpack-cli": "^4.10.0"
}
}
As a side-note, the script "yarn run build-babel" doesn't work either. This script worked before I installed Webpack.
Any advice is appreciated! :)
I have an issue with my app, everything was working fine until i ran npm run audit fix force then when i ran my app after this i am getting the error message below related to svg file.
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
i don't understand what went wrong.
Can someone help me, please?
package.json
{
"name": "myskillreactapp",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"#babel/preset-env": "^7.15.8",
"bootstrap": "^5.0.0-beta3",
"bootstrap-dark-5": "^1.1.3",
"font-awesome": "^4.7.0",
"next": "^10.0.4",
"next-images": "^1.8.1",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-icons": "^4.3.1",
"react-placeholder": "^4.1.0"
},
"devDependencies": {
"babel-plugin-inline-react-svg": "^2.0.1",
"eslint": "7.32.0",
"eslint-config-next": "^0.2.4",
"file-loader": "^6.2.0",
"sass": "^1.43.3"
}
}
next-config.js
const webpack = require('webpack');
module.exports = {
reactStrictMode: true,
entry: './src/index.js',
module: {
rules: [
//...
{
test: /\.(png|jp(e*)g|svg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'images/[hash]-[name].[ext]',
},
},
],
},
],
},
//...
};
_app.js
//import 'bootstrap/dist/css/bootstrap.css';
//import '/node_modules/bootstrap/scss/bootstrap.scss';
import '../styles/globals.scss';
import '../styles/Home.module.scss';
import 'font-awesome/css/font-awesome.min.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
The got solved by running npm run audit fix force again and it reverted back to normal. hope it helps someone. Thx
Leo
I got this starting point app that was given to me, and I have to add react to it.
Its a basic node application with this sctructure:
MyProject
src
scripts
index.js
styles
index.scss
index.html
webpack
webpack.common.js
webpack.config.dev.js
webpack.config.prod.js
.babelrc
And I also got this package.json:
{
"name": "frontend-assessment-test",
"version": "1.0.0",
"description": "A frontend assessment test for our new pirates, which are willing to come on board.",
"scripts": {
"build": "cross-env NODE_ENV=production webpack --config webpack/webpack.config.prod.js --colors",
"start": "webpack-dev-server --open --config webpack/webpack.config.dev.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/holidaypirates/frontend-assessment-test"
},
"author": "HolidayPirates",
"license": "MIT",
"bugs": {
"url": "https://github.com/holidaypirates/frontend-assessment-test/issues"
},
"devDependencies": {
"#babel/core": "^7.6.4",
"#babel/plugin-proposal-class-properties": "^7.5.5",
"#babel/plugin-syntax-dynamic-import": "^7.2.0",
"#babel/preset-env": "^7.6.3",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^5.0.4",
"cross-env": "^6.0.3",
"css-loader": "^3.2.0",
"eslint": "^6.5.1",
"eslint-loader": "^3.0.2",
"file-loader": "^4.2.0",
"html-webpack-plugin": "^4.0.0-beta.8",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "^4.13.0",
"sass-loader": "^8.0.0",
"style-loader": "^1.0.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.9.0",
"webpack-merge": "^4.2.2"
},
"dependencies": {
"#babel/polyfill": "^7.6.0",
"core-js": "^3.3.3"
}
}
The babel file webpack.common.js has this configuration:
module.exports = {
entry: {
app: Path.resolve(__dirname, '../src/scripts/index.js')
},
output: {
path: Path.join(__dirname, '../build'),
filename: 'js/[name].js'
},
optimization: {
splitChunks: {
chunks: 'all',
name: false
}
},
plugins: [
new CleanWebpackPlugin(),
new CopyWebpackPlugin([
{ from: Path.resolve(__dirname, '../public'), to: 'public' }
]),
new HtmlWebpackPlugin({
template: Path.resolve(__dirname, '../src/index.html')
})
],
resolve: {
alias: {
'~': Path.resolve(__dirname, '../src')
}
},
module: {
rules: [
{
test: /\.mjs$/,
include: /node_modules/,
type: 'javascript/auto'
},
{
test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
use: {
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}
},
]
}
};
So because I saw threre is babel and style loader added to the webpack, if I would just install react and react-dom I could then start using react, if I would, in the index.js file import react and try to render a basic component.
But i get an error that Module build failed (from ./node_modules/babel-loader/lib/index.js):
Any idea what should I change in webpack config or which other package other than react
and react-dom in order to use react in index.js?
Thanks.
This code base will not support react js. Babel is used to converted the non understandable JS parts(mostly es6 or more) to es5. Simple babel configuration will not work in your case, every library has their own way of syntax.
For example, in order to use the react you should be installing babel-preset-react which is mandatory for react.
The above mentioned will understand the jsx and react functionalities and converts to es5.
Install react first, see the hello world is working then try to add your node.js project into that react, try to add small chunk continuously and see the result
My personal opinion if possible, keep UI(react) and backend(node) separate
I'm kind of desperate here.
I'm working on a React application and use webpack to compile my bundle.js.
The problem is when i try to compile it for "production" i end up with a really nasty error :
"Minified React error #105; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=105&args[]=HardwareKeyboardArrowDown for the full message or use the non-minified dev environment for full errors and additional helpful warnings."
Followed by a bunch of
"Uncaught TypeError: Cannot read property '__reactInternalInstance$qw6tjofxg1o' of null"
When i set my node.env to developement ('NODE_ENV': JSON.stringify('developement') ), it's working fine.
The link in the error says : "A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object" but i don't have any problem in dev mode, so i don't think its coming from my code and i can't find where i should look to solve this problem since dev mode doesn't tell anything more to me...
Here are my webpack config & package.json :
const webpack = require('webpack');
const path = require('path');
const buildPath = path.resolve(__dirname, 'build');
const nodeModulesPath = path.resolve(__dirname, 'node_modules');
const TransferWebpackPlugin = require('transfer-webpack-plugin');
const config = {
entry: [
'./src/app/app.js'
],
// Render source-map file for final build
devtool: 'source-map',
debug: true,
// output config
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/public/'
},
plugins: [
// Define production build to allow React to strip out unnecessary checks
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': JSON.stringify('production')
}
}),
// Minify the bundle
new webpack.optimize.UglifyJsPlugin({
compress: {
// suppresses warnings, usually from module minification
warnings: false,
},
}),
// Allows error warnings but does not stop compiling.
new webpack.NoErrorsPlugin(),
// Transfer Files
],
module: {
loaders: [
{
test: /\.js$/, // All .js files
loaders: ['babel-loader'], // react-hot is like browser sync and babel loads jsx and es6-7
exclude: [nodeModulesPath],
},
{
test: /\.css$/,
loader: 'style-loader!css-loader',
include: /flexboxgrid/
},
{
test: /\.json$/, loader: "json-loader",
},
{ test: /\.scss?$/,
loader: 'style!css!sass',
include: path.join(__dirname, 'src', 'styles') },
{ test: /\.png$/,
loader: 'file' },
{ test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file'}
],
resolve: {
extensions: ['', '.js', '.jsx', '.css', '.json']
}
},
};
module.exports = config;
{
"name": "material-ui-example-webpack",
"version": "0.16.0",
"description": "Sample project that uses Material-UI",
"repository": {
"type": "git",
"url": "https://github.com/callemall/material-ui.git"
},
"scripts": {
"start": "webpack-dev-server --config webpack-dev-server.config.js --host $IP --port $PORT --hot --progress --inline --colors",
"clean-public": "npm run remove-public && mkdir public",
"remove-public": "node_modules/.bin/rimraf ./public",
"build:html": "babel-node tools/buildHtml.js",
"heroku-prebuild": "npm install && npm-run-all clean-public build:html",
"heroku-postbuild": "babel-node tools/build.js",
"prod-start": "babel-node tools/publicServer.js"
},
"private": true,
"devDependencies": {
"babel-core": "^6.18.2",
"babel-loader": "^6.2.8",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-2": "^6.18.0",
"html-webpack-plugin": "^2.24.1",
"npm-run-all": "1.8.0",
"redux-devtools": "^3.4.0",
"redux-devtools-dock-monitor": "^1.1.2",
"redux-devtools-log-monitor": "^1.3.0",
"rimraf": "2.5.2",
"transfer-webpack-plugin": "^0.1.4",
"webpack": "^1.13.3",
"webpack-dev-server": "^1.16.2"
},
"dependencies": {
"axios": "^0.16.1",
"babel-cli": "6.8.0",
"babel-loader": "^6.2.8",
"babel-polyfill": "6.8.0",
"babel-preset-es2015": "6.6.0",
"babel-preset-react": "6.5.0",
"babel-preset-stage-2": "^6.24.1",
"cheerio": "^0.20.0",
"colors": "1.1.2",
"compression": "^1.6.1",
"css-loader": "^0.27.3",
"express": "^4.15.2",
"json-loader": "^0.5.4",
"lint": "^1.1.2",
"material-ui": "^0.17.1",
"ncp": "^2.0.0",
"npm-run-all": "1.8.0",
"open": "0.0.5",
"react": "^15.4.1",
"react-component-queries": "^2.1.1",
"react-dom": "^15.4.1",
"react-fittext": "https://github.com/gianu/react-fittext",
"react-flexbox-grid": "^1.0.2",
"react-html-parser": "^1.0.3",
"react-masonry-component": "^5.0.5",
"react-redux": "^5.0.4",
"react-responsive": "^1.2.7",
"react-router": "^2.0.0-rc5",
"react-router-dom": "^4.0.0",
"react-sizeme": "^2.3.1",
"react-tap-event-plugin": "^2.0.1",
"redux": "^3.6.0",
"redux-form": "^6.6.3",
"redux-promise": "^0.5.3",
"rimraf": "2.5.2",
"serve-favicon": "^2.3.0",
"style-loader": "^0.16.0",
"transfer-webpack-plugin": "^0.1.4",
"webpack": "^1.13.3"
}
}
buildHtml script :
import fs from 'fs';
import cheerio from 'cheerio';
import colors from 'colors';
/*eslint-disable no-console */
console.log("buildHTML.js start");
fs.readFile('src/index.html', 'utf8', (err, markup) => {
if (err) {
return console.log(err);
}
const $ = cheerio.load(markup);
$('head').prepend('');
fs.writeFile('public/index.html', $.html(), 'utf8', function (err) {
if (err) {
return console.log(err);
}
console.log('index.html written to /public'.green);
});
});
And then build.js
/*eslint-disable no-console */
import webpack from 'webpack';
import webpackConfig from '../webpack-production.config';
import colors from 'colors';
import ncp from 'ncp';
process.env.NODE_ENV = 'production';
console.log("build.js start");
//Static files to import in /public (images/css)
var source = [["src/images","public/images"],["src/css","public/css"]];
function copyStaticFiles(path){
ncp(path[0], path[1], function (err) {
if (err) {
return console.error(err);
}})
}
console.log('Generating minified bundle for production via Webpack...'.blue);
webpack(webpackConfig).run((err, stats) => {
if (err) { // so a fatal error occurred. Stop here.
console.log(err.bold.red);
return 1;
}
const jsonStats = stats.toJson();
if (jsonStats.hasErrors) {
return jsonStats.errors.map(error => console.log(error.red));
}
if (jsonStats.hasWarnings) {
console.log('Webpack generated the following warnings: '.bold.yellow);
jsonStats.warnings.map(warning => console.log(warning.yellow));
}
console.log(`Webpack stats: ${stats}`);
source.forEach(copyStaticFiles);
console.log('Your app has been compiled in production mode and written to /public.'.green);
return 0;
});
I don't even know where to start and i can't find any documentation about this kind of errors.
I can provide more informations if needed.
Thanks for reading me
Ok so i dont have a object with a HardwareKeyboardArrowDown so i went looking in my dependencies and i found that it came from the matérial-ui dependency.
I forced the version 17.4 in my package.json and it worked !
The message gave you the name of the function (component) that returns the invalid object. HardwareKeyboardArrowDown.
So you should look at the return of its render function and make sure you return a valid React element (or null)
That means no undefined, array etc..