I am getting the following error
external_"react":1 Uncaught ReferenceError: react is not defined
at eval (external_"react":1)
at Object.react (bundle.js:120)
at __webpack_require__ (bundle.js:20)
at eval (client.js:2)
at Module../src/client.js (bundle.js:97)
at __webpack_require__ (bundle.js:20)
at bundle.js:84
at bundle.js:87
eval # external_"react":1
react # bundle.js:120
__webpack_require__ # bundle.js:20
eval # client.js:2
./src/client.js # bundle.js:97
__webpack_require__ # bundle.js:20
(anonymous) # bundle.js:84
(anonymous) # bundle.js:87
I have read many articles on here about how to solve, but nothing works.
My webpack.config.js is as follows :
const isDevelopment = process.env.NODE_ENV === 'development';
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const isomorphicRules = [
{
test: /\.(js?|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react'
]
}
}
},
{
test: /\.s[ac]ss$/i,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
modules: true
}
},
{
loader: 'sass-loader',
options: {
// Prefer `dart-sass`
implementation: require('sass'),
sassOptions: {
indentWidth: 4,
includePaths: ['public'],
},
},
}
]
},
];
const client = {
entry: './src/client.js',
output: {
path: path.join(__dirname, './src/public/dist/'),
publicPath: '/dist',
filename: 'bundle.js'
},
module: {
rules: isomorphicRules,
},
externals: ["react", "react-dom"],
plugins: [
new HtmlWebpackPlugin({
template: '!!raw-loader!' + path.join(__dirname, './src/views/clientside.ejs'),
filename: 'clientside.ejs',
inject: 'body'
})
]
};
const server = {
entry: './src/server.js',
output: {
path: path.join(__dirname, './src/public/dist/'),
filename: 'server.js'
},
module: {
rules: isomorphicRules
},
target: 'node',
externals: [nodeExternals(), "react", "react-dom"],
plugins: [
new HtmlWebpackPlugin({
template: '!!raw-loader!' + path.join(__dirname, './src/views/serverside.ejs'),
filename: 'serverside.ejs' // this line decide the extension of output file.
})
]
};
module.exports = [
client,
server,
];
I am stumped as I have added react as an external.
For good measure here is my package.json
{
"name": "webtest",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"abstract-syntax-tree": "^2.9.3",
"bootstrap": "^4.5.1",
"compression": "^1.7.4",
"dotenv": "^8.2.0",
"ejs": "^3.1.3",
"express": "^4.17.1",
"fabric": "^4.1.0",
"form-data": "^3.0.0",
"formidable": "^1.2.2",
"govuk-frontend": "^3.8.1",
"highlight.js": "^10.1.2",
"moment": "^2.27.0",
"node-fetch": "^2.6.0",
"react": "^16.13.1",
"react-bootstrap": "^1.3.0",
"react-dom": "^16.13.1",
"react-dom-server": "0.0.5",
"react-html-parser": "^2.0.2",
"react-json-view": "^1.19.1",
"react-router-dom": "^5.2.0",
"react-script-tag": "^1.1.2",
"react-scripts": "^3.4.3"
},
"scripts": {
"webpack": "webpack --mode development --config webpack.config.js",
"dev": "set NODE_ENV=development && webpack --mode development --config webpack.config.js && nodemon --exec babel-node src/index.js"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "^7.11.1",
"#babel/node": "^7.10.5",
"#babel/plugin-proposal-class-properties": "^7.10.4",
"#babel/polyfill": "^7.10.4",
"#babel/preset-env": "^7.11.0",
"#babel/preset-react": "^7.10.4",
"babel-loader": "^8.1.0",
"babel-plugin-css-modules-transform": "^1.6.2",
"cross-env": "^7.0.2",
"css-loader": "^4.2.2",
"dart-sass": "^1.25.0",
"ejs-webpack-loader": "^2.2.2",
"file-loader": "^6.0.0",
"html-loader": "^1.3.0",
"html-webpack-plugin": "^4.4.1",
"mini-css-extract-plugin": "^0.10.0",
"node-sass": "^4.14.1",
"nodemon": "^2.0.4",
"nodemon-webpack-plugin": "^4.3.2",
"raw-loader": "^4.0.1",
"sass": "^1.26.10",
"sass-loader": "^10.0.1",
"style-loader": "^1.2.1",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12",
"webpack-node-externals": "^1.7.2"
}
}
I am using the npm start dev script to launch.
The rendered html is as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<title>JSON Forms Demo</title>
</head>
<body>
<div id="root">
</div>
<script src="/dist/bundle.js"></script></body>
</html>
So it is clear to me the problem is that react is not defined. My question is why not?
My client.js looks like
import React from 'react';
import ReactDOM from 'react-dom';
import ClientApp from './clientApp';
ReactDOM.render(<ClientApp />, document.getElementById('root'));
And clientApp is as follows :
import React, { Component } from 'react';
class ClientApp extends Component {
render() {
return (
<div>
<h1>Hello World from Client Side App</h1>
</div>
);
}
}
export default ClientApp;
Also my .babelrc file looks like
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
So I feel like I've covered all the bases with what I've read on here and on the webpack website, but I clearly have missed something and would be most grateful if the panel could take a look.
Thanks to tmhao2005, yuRa and Freestyle09. It was driving me spare.
I removed the external directive from the webpack config and it works.
Related
I have a react app with webpack recently upgraded to version 5.
I am getting the following error and need help in fixing it
Uncaught (in promise) TypeError: crypto.createSign is not a function
at Object.sign (index.js:151)
at Object.jwsSign [as sign] (sign-stream.js:32)
at GoogleToken.requestToken (index.js:225)
at GoogleToken.getTokenAsyncInner (index.js:163)
at GoogleToken.getTokenAsync (index.js:142)
at GoogleToken.getToken (index.js:94)
at JWT.refreshTokenNoCache (jwtclient.js:158)
at JWT.refreshToken (oauth2client.js:143)
at JWT.authorizeAsync (jwtclient.js:139)
at JWT.authorize (jwtclient.js:135)
when the following code is executed (The credentials are correct)
const { GoogleSpreadsheet } = require("google-spreadsheet");
.
.
.
let submitOrderDetails = async () => {
const SPREADSHEET_ID = "working-id-here";
const doc = new GoogleSpreadsheet(SPREADSHEET_ID);
// this fails
await doc.useServiceAccountAuth({
client_email: creds.client_email,
private_key: creds.private_key,
});
.
.
.
}
webpack.config.json
const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require("path");
const webpack = require("webpack");
module.exports = {
context: __dirname,
entry: "./src/index.js",
output: {
path: path.join(__dirname, "build"),
filename: "main.js",
publicPath: "/",
},
target: "web",
devServer: {
historyApiFallback: true,
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: "babel-loader",
},
{
test: /\.scss$/,
use: [
"style-loader", //3. Inject styles into DOM
"css-loader", //2. Turns css into commonjs
"sass-loader", //1. Turns sass into css
],
},
{
test: /\.(png|jp?g|svg|gif)?$/,
use: {
loader: "file-loader",
},
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: path.join(__dirname, "public/index.html"),
filename: "index.html",
}),
new webpack.ProvidePlugin({
process: "process/browser",
}),
],
resolve: {
fallback: {
fs: false,
tls: false,
net: false,
path: false,
zlib: false,
http: false,
https: false,
stream: false,
crypto: false,
"crypto-browserify": require.resolve("crypto-browserify"),
os: require.resolve("os-browserify/browser"),
child_process: false,
},
},
};
package.json
{
"name": "my-project",
"version": "0.1.0",
"private": true,
"dependencies": {
"crypto": "^1.0.1",
"crypto-browserify": "^3.12.0",
"fs": "0.0.1-security",
"google-spreadsheet": "^3.2.0",
"googleapis": "^67.0.0",
"http": "0.0.1-security",
"https-browserify": "^1.0.0",
"net": "^1.0.2",
"os": "^0.1.2",
"path": "^0.12.7",
"prettier": "^2.5.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-router-dom": "^5.3.0",
"react-scripts": "4.0.1",
"stream": "0.0.2",
"tls": "0.0.1",
"zlib": "^1.0.5"
},
"scripts": {
"start": "webpack serve --mode development",
"build": "webpack --mode production",
"pretty": "prettier --write \"./**/*.*\""
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "^7.16.5",
"#babel/plugin-proposal-class-properties": "^7.16.5",
"#babel/plugin-transform-runtime": "^7.16.5",
"#babel/preset-env": "^7.16.5",
"#babel/preset-react": "^7.16.5",
"babel-loader": "^8.2.3",
"clean-webpack-plugin": "^4.0.0",
"css-loader": "^5.2.7",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.4.5",
"node-sass": "^6.0.1",
"optimize-css-assets-webpack-plugin": "^6.0.1",
"process": "^0.11.10",
"sass-loader": "^12.4.0",
"style-loader": "^2.0.0",
"terser-webpack-plugin": "^5.3.0",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^3.11.3",
"webpack-merge": "^5.8.0"
}
}
Answering my own question. I updated the webpack config by adding fallbacks.
Here are the updated webpack.config.json and package.json
webpack.config.json
const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require("path");
const webpack = require("webpack");
module.exports = {
context: __dirname,
entry: "./src/index.js",
output: {
path: path.join(__dirname, "build"),
filename: "main.js",
publicPath: "/",
},
target: "web",
devServer: {
historyApiFallback: true,
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: "babel-loader",
},
{
test: /\.scss$/,
use: [
"style-loader", //3. Inject styles into DOM
"css-loader", //2. Turns css into commonjs
"sass-loader", //1. Turns sass into css
],
},
{
test: /\.(png|jp?g|svg|gif)?$/,
use: {
loader: "file-loader",
},
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: path.join(__dirname, "public/index.html"),
filename: "index.html",
}),
new webpack.ProvidePlugin({
process: "process/browser",
Buffer: ["buffer", "Buffer"],
}),
],
resolve: {
fallback: {
fs: false,
tls: "empty",
child_process: false,
util: require.resolve("util/"),
buffer: require.resolve("buffer"),
assert: require.resolve("assert/"),
http: require.resolve("stream-http"),
path: require.resolve("path-browserify"),
https: require.resolve("https-browserify"),
os: require.resolve("os-browserify/browser"),
stream: require.resolve("stream-browserify"),
crypto: require.resolve("crypto-browserify"),
"crypto-browserify": require.resolve("crypto-browserify"),
},
},
};
package.json
{
"name": "sigmaprints",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "webpack serve --mode development",
"build": "webpack --mode production",
"pretty": "prettier --write \"./**/*.*\""
},
"devDependencies": {
"#babel/core": "^7.12.1",
"#babel/plugin-proposal-class-properties": "^7.12.1",
"#babel/plugin-transform-runtime": "^7.14.5",
"#babel/preset-env": "^7.12.1",
"#babel/preset-react": "^7.12.1",
"babel-loader": "^8.1.0",
"clean-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^6.2.1",
"cross-env": "^7.0.2",
"css-loader": "^5.0.0",
"file-loader": "^6.2.0",
"css-minimizer-webpack-plugin": "^1.1.5",
"process": "0.11.10",
"html-webpack-plugin": "^4.5.0",
"node-sass": "^4.14.1",
"optimize-css-assets-webpack-plugin": "^5.0.4",
"prettier": "^2.1.2",
"sass-loader": "^10.0.3",
"style-loader": "^2.0.0",
"terser-webpack-plugin": "^4.2.3",
"webpack": "^5.1.2",
"webpack-cli": "^4.0.0",
"webpack-dev-server": "^3.11.0",
"webpack-merge": "^5.2.0"
},
"browser": {
"crypto": false
},
"dependencies": {
"assert": "^2.0.0",
"buffer": "^6.0.3",
"crypto-browserify": "^3.12.0",
"google-spreadsheet": "^3.1.15",
"http-browserify": "^1.7.0",
"https-browserify": "^1.0.0",
"net": "^1.0.2",
"os-browserify": "^0.3.0",
"path-browserify": "^1.0.1",
"react": "^16.14.0",
"react-dom": "^16.14.0",
"react-router-dom": "^5.2.0",
"stream-browserify": "^3.0.0",
"stream-http": "^3.2.0",
"tls": "0.0.1",
"util": "^0.12.4"
}
}
I am setting up a React app with babel and webpack. The app works fine on chrome and other browsers except internet exlorer11.
Here is my package.json
{
"name": "xai",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"webpack": "webpack",
"start": "webpack serve"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all",
"not ie < 11",
"ie 11"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version",
"ie 11"
]
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.14.3",
"#babel/node": "^7.14.2",
"#babel/plugin-proposal-class-properties": "^7.13.0",
"#babel/preset-env": "^7.14.4",
"#babel/preset-react": "^7.13.13",
"#fortawesome/fontawesome-free": "^5.15.3",
"babel-loader": "^8.2.2",
"css-loader": "^5.2.6",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.1",
"image-webpack-loader": "^7.0.1",
"path": "^0.12.7",
"style-loader": "^2.0.0",
"webpack": "^5.38.1",
"webpack-cli": "^4.7.0",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"#material-ui/core": "^4.11.4",
"axios": "^0.21.1",
"bootstrap": "^5.0.1",
"copy-to-clipboard": "^3.3.1",
"fast-text-encoding": "^1.0.3",
"firebase": "^8.6.3",
"font-awesome": "^4.7.0",
"font-awesome-webpack": "0.0.5-beta.2",
"gh-pages": "^3.2.0",
"history": "^5.0.0",
"hookrouter": "^1.2.5",
"lodash": "^4.17.21",
"markdown-loader": "^6.0.0",
"max-validator": "^1.2.1",
"node-sass": "^6.0.0",
"raw-loader": "^4.0.2",
"react": "^17.0.2",
"react-animations": "^1.0.0",
"react-app-polyfill": "^2.0.0",
"react-beforeunload": "^2.5.1",
"react-beforeunload-component": "^1.2.3",
"react-dom": "^17.0.2",
"react-likert-scale": "^4.1.1",
"react-radio-buttons": "^1.2.2",
"react-router-dom": "^5.2.0",
"react-toastify": "^7.0.4",
"react-tooltip": "^4.2.21",
"reactstrap": "^8.9.0",
"sass-loader": "^11.1.1",
"url-loader": "^4.1.1",
"uuid": "^8.3.2"
}
}
And webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: path.join(__dirname, "src", "index.js"),
output: { path: path.join(__dirname, "build"), filename: "index.bundle.js" },
mode: process.env.NODE_ENV || "development",
resolve: {
modules: [path.resolve(__dirname, "src/"), "node_modules"],
extensions: ["*", ".js", ".jsx", ".json"],
symlinks: false,
cacheWithContext: false,
},
devServer: { contentBase: path.join(__dirname, "src") },
module: {
rules: [
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: "url-loader?limit=10000&mimetype=application/font-woff",
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: "file-loader",
},
{ test: /\.md$/, use: "raw-loader" },
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
{
test: /\.(css|scss)$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.(jpg|jpeg|png|gif|mp3|svg)$/,
use: ["file-loader"],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, "src", "index.html"),
}),
],
};
and I use this config for .babelrc
{
"presets": ["#babel/preset-env", "#babel/react"],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
The problem is that I used to have the app load(with broken routing when I use CRA). Now I only get a blank page with SCRIPT1006: Expected '('. I am wondering if you could have a workaround to solve this error
You can try to remove the browserslist and use target: ['web', 'es5'] to support IE 11. It will convert your code to ES5 which works in IE 11. For more information, you can refer to this answer and this doc.
I follow the steps in this blog to setup a React app with Webpack and Babel, then I add target: ['web', 'es5'] in webpack.config.js like below and it works well in IE 11. You can also try:
module.exports = {
// ...
target: ['web', 'es5'],
};
I tried to setup my own toolchain to build a React app. I'm using Webpack with Typescript React.
package.json
{
"name": "library2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"lint": "eslint '**/*.{tsx,js,ts}'",
"lint:fix": "eslint --fix '**/*.{tsx,js,ts}'",
"start": "webpack-dev-server --mode development"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"pg": "^8.3.0",
"prettier": "^2.0.5",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"typescript": "^3.9.5"
},
"devDependencies": {
"#babel/cli": "^7.10.4",
"#babel/core": "^7.10.4",
"#babel/plugin-proposal-class-properties": "^7.10.4",
"#babel/preset-env": "^7.10.4",
"#babel/preset-react": "^7.10.4",
"#types/node": "^14.0.20",
"#types/react": "^16.9.41",
"#types/react-dom": "^16.9.8",
"#typescript-eslint/eslint-plugin": "^3.1.0",
"#typescript-eslint/parser": "^3.1.0",
"babel-loader": "^8.1.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "^3.6.0",
"eslint": "^6.8.0",
"eslint-config-airbnb": "^18.1.0",
"eslint-plugin-import": "^2.21.1",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.20.0",
"eslint-plugin-react-hooks": "^2.5.1",
"style-loader": "^1.2.1",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
}
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/App.tsx',
mode: 'development',
module: {
rules: [
{
test: /\.(|ts|tsx|js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react',
],
plugins: [
'#babel/plugin-proposal-class-properties',
],
},
},
},
{ // rules for css
test: /\.(css|scss)$/,
use: ['style-loader', 'css-loader'],
},
],
},
resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'] },
output: {
path: path.resolve(__dirname, 'dist/'),
publicPath: '/dist/',
filename: 'bundle.js',
},
devServer: {
contentBase: path.join(__dirname, 'public/'),
port: 3000,
publicPath: 'http://localhost:3000/dist/',
hotOnly: true,
},
plugins: [new webpack.HotModuleReplacementPlugin()],
};
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="main"></div>
<script src="../dist/bundle.js"></script>
</body>
</html>
App.tsx
import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
render(<Hello />, document.querySelector('#main'));
Hello.tsx
import React from 'react';
import './hello.scss';
export default class Hello extends React.Component {
vark: number;
test() {
this.vark = 1;
}
render() {
return (
<div className="hello">Hello!</div>
);
}
}
I get the following error when webpack builds (npm run start):
ERROR in ./src/Hello.tsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/JAAI/Desktop/Library2/src/Hello.tsx: Unexpected token (5:6)
3 |
4 | export default class Hello extends React.Component {
> 5 | vark: number;
| ^
6 |
7 | test() {
8 | this.vark = 1;
at Object._raise (/Users/JAAI/Desktop/Library2/node_modules/#babel/parser/lib/index.js:757:17)
at Object.raiseWithData (/Users/JAAI/Desktop/Library2/node_modules/#babel/parser/lib/index.js:750:17)
at Object.raise (/Users/JAAI/Desktop/Library2/node_modules/#babel/parser/lib/index.js:744:17)
at Object.unexpected (/Users/JAAI/Desktop/Library2/node_modules/#babel/parser/lib/index.js:8834:16)
at Object.parseClassMemberWithIsStatic (/Users/JAAI/Desktop/Library2/node_modules/#babel/parser/lib/index.js:12169:12)
at Object.parseClassMember (/Users/JAAI/Desktop/Library2/node_modules/#babel/parser/lib/index.js:12062:10)
at /Users/JAAI/Desktop/Library2/node_modules/#babel/parser/lib/index.js:12007:14
at Object.withTopicForbiddingContext (/Users/JAAI/Desktop/Library2/node_modules/#babel/parser/lib/index.js:11078:14)
at Object.parseClassBody (/Users/JAAI/Desktop/Library2/node_modules/#babel/parser/lib/index.js:11984:10)
at Object.parseClass (/Users/JAAI/Desktop/Library2/node_modules/#babel/parser/lib/index.js:11958:22)
# ./src/App.tsx 3:0-28 4:41-46
ℹ 「wdm」: Failed to compile.
At first I thought this was because the Webpack env and react presets didn't allow for class properties so I included the class properties plugin but the error persisted. Note that if I remove that line it builds successfully.
I'm trying to Unit test my React component which imports another component that contains .png file. Because of this image, my test suits are failing to run.
I tried all the possible solutions with the below configuration, still no luck.
Please suggest, this is my project configuration.
This is my jest.config.json
{
"testRegex": "((\\.|/*.)(spec))\\.js?$"
}
My package.json
{
"name": "Application name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --config ./webpack.config.js --mode development",
"test": "jest"
},
"jest": {
"moduleNameMapper": {
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "identity-obj-proxy"
}
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.8.7",
"#babel/polyfill": "^7.10.1",
"#babel/preset-env": "^7.10.2",
"#babel/preset-react": "^7.8.3",
"axios-mock-adapter": "^1.18.1",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.0.6",
"css-loader": "^3.5.3",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"eslint": "^6.8.0",
"eslint-config-airbnb": "^18.1.0",
"eslint-config-prettier": "^6.11.0",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-prettier": "^3.1.3",
"eslint-plugin-react": "^7.19.0",
"eslint-plugin-react-hooks": "^2.5.0",
"file-loader": "^6.0.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^26.0.1",
"prettier": "^2.0.5",
"react-hot-loader": "^4.12.19",
"redux-mock-store": "^1.5.4",
"style-loader": "^1.2.1",
"url-loader": "^4.1.0",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
},
"dependencies": {
"#material-ui/core": "^4.10.2",
"#material-ui/icons": "^4.9.1",
"#material-ui/lab": "^4.0.0-alpha.56",
"axios": "^0.19.2",
"core-js": "^3.6.5",
"d3-sankey-diagram": "^0.7.3",
"husky": "^4.2.5",
"prop-types": "^15.7.2",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-google-charts": "^3.0.15",
"react-intl": "^4.6.3",
"react-redux": "^7.2.0",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-test-renderer": "^16.13.1",
"redux": "^4.0.5",
"redux-saga": "^1.1.3",
"regenerator-runtime": "^0.13.5"
}
}
My Webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: ['./src/index.js', '#babel/polyfill'],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.css$/i,
exclude: /node_modules/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
{
test: /\.(jpe?g|gif|png|svg)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 10000,
},
},
],
},
{
test: /\.(gif|png|jpe?g)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'assets/images/',
},
},
],
},
],
// loaders: [{ test: /\.jsx?$/, loader: 'babel' }],
},
devServer: {
historyApiFallback: true,
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: path.join(__dirname, '/dist'),
filename: 'bundle.js',
publicPath: '/',
},
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
contentBase: './dist',
hot: true,
},
};
My .babelrc file
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
Finally my test file:
import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import MyPackage from '../Components/index';
Enzyme.configure({ adapter: new Adapter() });
describe('Some name', () => {
it('This should be loaded', () => {
const wrapper = shallow(<MyPackage />);
const x= wrapper.find('#selector').debug();
expect(x.prop('length')).toBe(1);
});
});
I tried adding mocks/fileMock.js with
export default '';
and mocks/styleMocks.js
module.exports = {};
still I see this error -
● Test suite failed to run
D:\ReactStuff\folder\myproject\src\assets\images\mylogo.png:1
�PNG
SyntaxError: Invalid or unexpected token
1 | import React from 'react';
> 2 | import { HeaderLogo} from '../assets/images/mylogo.png';
| ^
3 |
4 | const Header = () => {
5 | return (
What am I missing here. Please suggest
I have no problem whatsoever working on the dev env, hot reloading and everything works fine. Trying to make a production build its proving to be quite challenging, getting nothing but a blank page. There seems to be similar questions on here but I'm not using any html as an entry point. Thanks in advance.
package.json
{
"name": "dc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack-dev-server -d --content-base public --inline --hot --host 0.0.0.0",
"prod": "webpack -p --progress --config prod.config.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"axios": "^0.9.1",
"babel-core": "^6.7.2",
"babel-loader": "^6.2.4",
"babel-polyfill": "^6.7.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-react-hmre": "^1.1.1",
"css-loader": "^0.23.1",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.8.5",
"history": "^2.0.1",
"isomorphic-fetch": "^2.2.1",
"node-sass": "^3.4.2",
"react": "^0.14.7",
"react-css-transition-replace": "^1.1.0",
"react-dom": "^0.14.7",
"react-hot-loader": "^1.3.0",
"react-redux": "^4.4.1",
"react-router": "^2.0.1",
"redux": "^3.3.1",
"redux-logger": "^2.6.1",
"redux-thunk": "^2.0.1",
"sass-loader": "^3.2.0",
"style-loader": "^0.13.1",
"webpack": "^1.12.14"
},
"dependencies": {
"axios": "^0.9.1",
"history": "^2.0.1",
"isomorphic-fetch": "^2.2.1",
"react": "^0.14.7",
"react-redux": "^4.4.1",
"react-router": "^2.0.1",
"redux": "^3.3.1"
}
}
production config
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry : ["./app/App.js"],
output : {
filename: "bundle.js",
publicPath: 'dist/',
path : path.resolve(__dirname, 'dist/')
},
devtool: 'source-map',
devServer: {
contentBase: 'dist/'
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"',
},
__DEVELOPMENT__: false,
}),
new webpack.optimize.OccurenceOrderPlugin(),
new ExtractTextPlugin("styles.css"),
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: true,
},
}),
],
module : {
loaders : [
{ test : /\.jsx?$/, loader : 'babel-loader',
query : {
presets : ['react', 'es2015', 'react-hmre']
}
},
{ test: /\.(jpg|png)$/, exclude: /node_modules/, loader: "file?name=images/[name].[ext]"},
{ test: /\.css$/, exclude: /node_modules/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") },
{ test: /\.scss$/, exclude: /node_modules/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader") }
]
}
};
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>lol</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="app"></div>
<script src="bundle.js"></script>
</body>
</html>
I have been working with a bit different solution. What I have been doing is bundling the files through webpack then use a koa server to serve a static file and then have a npm start script which sets NODE_ENV to production. Take a look:
package.json:
{
"name": "react",
"version": "1.0.0",
"description": "some description",
"main": "index.js",
"scripts": {
"test": "test",
"start": "NODE_ENV=production webpack --progress && NODE_ENV=production node server.js",
"dev": "webpack-dev-server --progress --colors --watch",
"build": "webpack --progress --watch"
},
"author": "your_name",
"license": "ISC",
"dependencies":{
"babel-core": "^6.7.2",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"copy-webpack-plugin": "^1.1.1",
"css-loader": "^0.23.1",
"extract-text-webpack-plugin": "^1.0.1",
"image-webpack-loader": "^1.6.3",
"json-loader": "^0.5.4",
"sass-loader": "^3.2.0",
"style-loader": "^0.13.0",
"koa": "2.0.0-alpha.3",
"koa-convert": "1.2.0",
"koa-static": "2.0.0",
"react": "^0.14.7",
"react-dom": "^0.14.7",
"webpack": "^1.12.14",
"webpack-dev-server": "^1.14.1"
}
}
server.js:
'use strict';
const port = process.env.PORT || 3000;
const Koa = require('koa');
const serve = require('koa-static');
const convert = require('koa-convert');
const app = new Koa();
const _use = app.use;
app.use = (x) => _use.call(app, convert(x));
app.use(serve('./build'));
const server = app.listen(port, function () {
let host = server.address().address;
let port = server.address().port;
console.log('listening at http://%s:%s', host, port);
});
and finaly webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: './main.js',
output: { path: __dirname + "/build/", filename: 'bundle.js' },
module: {
loaders: [
{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract("style", "css!sass?")
},
{
test: /\.json$/,
loader: "json"
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
}
]
},
plugins: [
new ExtractTextPlugin("main.css"),
new CopyWebpackPlugin([
{
from: __dirname + '/index.html',
to: __dirname + '/index.html'
},
])
]
};
If you will run those with an index.html file and an main.js file rendering some react to it it will run on production :) I recently wrote an article about how exactly my solution looks like. Feel free to take a look: https://medium.com/#TheBannik/get-ready-to-deploy-a-react-js-app-8f62c8e08282#.9gcd329h6