Cookies module not working in Electron app - reactjs

I am trying to return the cookies from the browser header but I cannot even get the module to work. I can run the app but I am getting error message: Error Alert. I'm using Node.JS with Electron + Webpack + React. This is my code:
var app = require('app');
var BrowserWindow = require('browser-window');
var http = require('http');
var Cookies = require('./node_modules/cookies');
require('crash-reporter').start();
app.on('window-all-closed', function() {
if (process.platform != 'darwin') {
app.quit();
}
});
app.on('ready', function() {
mainWindow = new BrowserWindow({
frame: true,
width: 1200,
resizable: false,
height: 800,
'web-preferences': {'web-security': false}});
mainWindow.setMenu(null);
mainWindow.loadUrl('file://' + __dirname + '/public/index.html');
mainWindow.openDevTools();
mainWindow.on('closed', function() {
mainWindow = null;
});
mainWindow.on.session.Cookies.get({}, function(error, Cookies) {
if (error) throw error;
console.log(Cookies);
});
});
Package.json:
{
"name": "BSB-app",
"version": "0.1.0",
"description": "",
"main": "main.js",
"devDependencies": {
"babel": "^6.5.2",
"babel-cli": "^6.6.0",
"babel-core": "^6.5.2",
"babel-loader": "^6.2.3",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-register": "^6.6.0",
"css-loader": "^0.23.1",
"electron-cookies": "^1.1.0",
"electron-packager": "^5.2.1",
"electron-rebuild": "^1.1.3",
"less": "^2.6.0",
"less-loader": "^2.2.2",
"node-libs-browser": "^1.0.0",
"style-loader": "^0.13.0",
"webpack": "^1.12.14",
"webpack-dev-server": "^1.14.1"
},
"dependencies": {
"babel-polyfill": "^6.6.1",
"electron-prebuilt": "^0.36.8",
"exports-loader": "^0.6.3",
"imports-loader": "^0.6.5",
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-redux": "^4.4.0",
"redux": "^3.3.1",
"whatwg-fetch": "^0.11.0"
},
"scripts": {
"start": "electron .",
"watch": "node_modules/.bin/webpack-dev-server",
"electron-rebuild": "node_modules/.bin/electron-rebuild"
}
}
Webpack.config.js:
const webpack = require('webpack');
const production = process.env.NODE_ENV === 'production';
module.exports = {
entry: {
app: ['webpack/hot/dev-server', './javascripts/entry.js']
},
output: {
path: './public/built',
filename: 'bundle.js',
publicPath: 'http://localhost:8080/built/'
},
devServer: {
contentBase: './public',
publicPath: 'http://localhost:8080/built/'
},
resolveLoader: {
modulesDirectories: [
'node_modules'
]
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel-loader', query: { presets: ['es2015', 'react'] }, exclude: /node_modules/ },
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.less$/, loader: 'style-loader!css-loader!less-loader'},
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': {NODE_ENV: JSON.stringify(process.env.NODE_ENV)},
}),
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
}),
new webpack.IgnorePlugin(new RegExp("^(fs|ipc)$"))
]
}

The electron-cookies package it is meant to be used in the renderer process, you're attempting to use it in the main/browser process. In the render process you should be able to do something like:
require('electron-cookies');
document.cookie = 'key=value; key2=value2';
// or to clear the cookies
document.clearCookies();

Related

./components/Avatar.tsx Error: Cannot find module '#babel/preset-stage-0'

After a few hours of research, I still haven't solved an issue I've been having with Babel and Webpack. ): I'm sure the solution is simple.
My .babelrc:
{
"presets": ["#babel/preset-env", "#babel/preset-react", "#babel/preset-stage-0"]
}
My package.json
{
"name": "sabrinasbase",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"chokidar": "^3.5.1",
"css-modules-typescript-loader": "^4.0.1",
"next": "10.0.5",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-particles-js": "^3.4.1",
"react-tsparticles": "^1.18.11",
"sass": "^1.32.5",
"three": "^0.124.0"
},
"devDependencies": {
"#babel/cli": "^7.12.10",
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"#babel/preset-react": "^7.12.10",
"#babel/preset-stage-0": "^7.8.3",
"#babel/register": "^7.12.10",
"#types/node": "^14.14.22",
"#types/react": "^17.0.0",
"babel-loader": "^8.2.2",
"typescript": "^4.1.3",
"url-loader": "^4.1.1",
"webpack": "^5.16.0",
"webpack-cli": "^4.4.0",
"webpack-dev-middleware": "^1.2.0",
"webpack-hot-middleware": "^2.0.0"
},
"resolutions": {
"#babel/core": "^7.12.10"
}
}
My webpack.config.js
var path = require("path");
module.exports = {
//mode: "production",
mode: "development",
devtool: "inline-source-map",
context: path.join(__dirname, "pages"),
entry: ["/_app.js" /*main*/],
output: {
filename: "./bundle.js", // in /dist
},
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: [".ts", ".tsx", ".js", ".css", ".scss"],
},
module: {
rules: [
{ test: /\.tsx?$/, loader: "ts-loader" },
{
test: /\.scss$/,
use: [
{ loader: "style-loader" }, // to inject the result into the DOM as a style block
{ loader: "css-modules-typescript-loader" }, // to generate a .d.ts module next to the .scss file (also requires a declaration.d.ts with "declare modules '*.scss';" in it to tell TypeScript that "import styles from './styles.scss';" means to load the module "./styles.scss.d.td")
{ loader: "css-loader", options: { modules: true } }, // to convert the resulting CSS to Javascript to be bundled (modules:true to rename CSS classes in output to cryptic identifiers, except if wrapped in a :global(...) pseudo class)
{ loader: "sass-loader" }, // to convert SASS to CSS
// NOTE: The first build after adding/removing/renaming CSS classes fails, since the newly generated .d.ts typescript module is picked up only later
],
},
{
test: /\.png|jpg|gif$/i,
use: [
{
loader: "url-loader",
options: {
limit: 8192,
},
},
],
},
{ test: /\.js|tsx|ts$/, loader: "babel-loader", exclude: /node_modules/ },
],
},
};
All I want to do is import a picture into a component. Originally I was getting Plugin/Preset files are not allowed to export objects, only functions error, but now I am getting vaguer errors that the module isn't working correctly. There were a few times that the Webpack would compile successfully, but the file I wanted to use wouldn't. Is there anything I am missing? I promise I am installing the preset-stage-0 package.
Error: Cannot find module '#babel/preset-stage-0'
Require stack:
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\compiled\babel\bundle.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\compiled\babel\code-frame.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\lib\typescript\diagnosticFormatter.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\lib\typescript\runTypeCheck.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\lib\verifyTypeScriptSetup.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\server\next-dev-server.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\server\next.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\server\lib\start-server.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\cli\next-dev.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\bin\next
at Array.map (<anonymous>)
at Generator.next (<anonymous>)
at loadFileChain.next (<anonymous>)
Not sure why you are getting this error
Here is my webpack which works as expected
Also, apologies in advance as I have done heck load of optimization to reduce bundle size
Webpack.config.base.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');
const CopyPlugin = require("copy-webpack-plugin");
const ServiceWorkerWebpackPlugin = require('serviceworker-webpack-plugin');
const {WebpackManifestPlugin} = require('webpack-manifest-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const PurifyCssPlugin = require('purifycss-webpack');
const glob = require("glob");
module.exports = {
target: 'web',
stats: 'verbose',
output: {
path: __dirname + '/dist',
filename: '[name].[hash].bundle.js'
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
},
{
test: /\.css$/,
use: [{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: './'
}
}, 'css-loader']
},
{
test: /\.scss$/,
use: [{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: './'
}
}, 'css-loader', 'sass-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
{
loader: 'image-webpack-loader',
options: {
bypassOnDebug: true, // webpack#1.x
disable: true, // webpack#2.x and newer
mozjpeg: {
progressive: true,
},
optipng: {
enabled: false,
},
pngquant: {
quality: [0.65, 0.90],
speed: 4
},
gifsicle: {
interlaced: false,
},
},
}
]
}
]
},
plugins: [
new CopyPlugin({
patterns: [
{from: "icons", to: "icons"},
{from: "./manifest.webmanifest", to: ""},
{from: "./.htaccess", to: ""},
{from: "./robots.txt", to: ""}
],
}),
new MiniCssExtractPlugin({
filename: "[name].[hash].css"
}),
new HtmlWebpackPlugin({
template: "./src/app/index.html",
favicon: "./src/assets/image/favicon.png",
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true
}
}),
new ServiceWorkerWebpackPlugin({
entry: path.join(__dirname, './src/app/serviceWorker/serviceWorkerInit.js'),
}),
new WebpackManifestPlugin({
fileName: 'asset-manifest.json', // Not to confuse with manifest.json
}),
new ESLintPlugin({files: './src/app/app.js'}),
new PurifyCssPlugin({
paths: [
...(glob.sync(`./src/app/*.html`)),
...(glob.sync(`./src/app/**/*.jsx`)),
...(glob.sync(`./dist/*.html`))
],
styleExtensions: ['.css','.scss'],
moduleExtensions: [".html"],
verbose: true,
purifyOptions: {
info: true,
minify: true,
whitelist: ["*purify*"]
},
})
]
};
Webpack.config.prod.js
const merge = require('webpack-merge');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const webpackBaseConfiguration = require('./webpack.config.base.js');
const TerserPlugin = require('terser-webpack-plugin')
const webpack = require('webpack');
const GLOBALS = {
'process.env.NODE_ENV': JSON.stringify('production'),
__DEV__: false
};
module.exports = merge(webpackBaseConfiguration,{
mode: 'production',
entry: [
'#babel/polyfill',
'./src/app/app.jsx'
],
devServer: {
contentBase: './dist'
},
optimization: {
splitChunks: {
chunks: 'all',
minSize: 20000,
maxSize: 0,
minChunks: 2,
maxAsyncRequests: 30,
maxInitialRequests: 30,
enforceSizeThreshold: 50000,
cacheGroups: {
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
reuseExistingChunk: true
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
},
usedExports: true,
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
ecma: 6,
},
}),
new OptimizeCSSAssetsPlugin()
]
},
plugins: [
new webpack.DefinePlugin(GLOBALS),
new CompressionPlugin({
algorithm: 'gzip',
minRatio: Number.MAX_SAFE_INTEGER
}),
new CompressionPlugin({
filename: "[path].br",
algorithm: "brotliCompress",
test: /\.(js|css|html|svg|png|svg|jpg|gif)$/,
deleteOriginalAssets: false,
minRatio: Number.MAX_SAFE_INTEGER
})
]
});
Webpack.config.dev.js
const merge = require('webpack-merge');
const webpackBaseConfiguration = require('./webpack.config.base');
const webpack = require('webpack');
module.exports = merge(webpackBaseConfiguration,{
mode: 'development',
output: {
publicPath: '/'
},
devServer: {
contentBase: './src',
historyApiFallback: true
},
devtool: 'cheap-module-eval-source-map',
entry: [
'#babel/polyfill',
'webpack-hot-middleware/client?reload=true',
'./src/app/app.jsx'
],
plugins: [
/*For hot deployment*/
new webpack.HotModuleReplacementPlugin()
]
});
package.json
{
"name": "Sample",
"version": "1.0.0",
"description": "React app",
"scripts": {
"clean": "rimraf dist",
"deploy": "node deploy",
"build:prod:deploy": "npm run clean && webpack --mode production --config webpack.config.prod.js && node deploy",
"build:prod": "npm run clean && webpack --mode production --config webpack.config.prod.js",
"build:dev": "webpack-dev-server --mode development --config webpack.config.dev.js --open --hot",
"start": "npm run build && npm run deploy",
"build": "npm run clean && webpack --mode production --config webpack.config.prod.js && npm run deploy"
},
"engines": {
"node": "14.x",
"npm": "6.x"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.12.1",
"#babel/core": "^7.2.2",
"#babel/node": "^7.2.2",
"#babel/plugin-proposal-class-properties": "^7.3.0",
"#babel/polyfill": "^7.2.5",
"#babel/preset-env": "^7.2.0",
"#babel/preset-react": "^7.0.0",
"#babel/register": "^7.0.0",
"#gfx/zopfli": "^1.0.15",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.0.4",
"brotli-webpack-plugin": "^1.1.0",
"compression-webpack-plugin": "^2.0.0",
"copy-webpack-plugin": "6.2.1",
"css-loader": "^2.1.0",
"eslint": "^7.18.0",
"eslint-webpack-plugin": "^2.4.1",
"file-loader": "^3.0.1",
"ftp-deploy": "^2.4.0",
"glob": "^7.1.6",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"image-minimizer-webpack-plugin": "^1.0.0",
"image-webpack-loader": "^7.0.1",
"imagemin-gifsicle": "^7.0.0",
"imagemin-jpegtran": "^7.0.0",
"imagemin-optipng": "^8.0.0",
"imagemin-svgo": "^8.0.0",
"mini-css-extract-plugin": "^0.5.0",
"node-sass": "^4.14.1",
"optimize-css-assets-webpack-plugin": "^5.0.1",
"purify-css": "^1.2.5",
"purifycss-webpack": "^0.7.0",
"rimraf": "^2.6.3",
"sass-loader": "^7.1.0",
"serviceworker-webpack-plugin": "^1.0.1",
"terser-webpack-plugin": "4.2.3",
"uglifyjs-webpack-plugin": "^2.1.1",
"webpack": "^4.40.0",
"webpack-cli": "^3.1.2",
"webpack-dev-middleware": "^3.5.2",
"webpack-dev-server": "^3.11.0",
"webpack-ftp-upload-plugin": "^1.0.3",
"webpack-hot-middleware": "^2.24.3",
"webpack-manifest-plugin": "^3.0.0",
"webpack-merge": "^4.2.1",
"workbox-cacheable-response": "^6.0.2",
"workbox-expiration": "^6.0.2",
"workbox-routing": "^6.0.2",
"workbox-strategies": "^6.0.2",
"workbox-webpack-plugin": "^6.0.2",
"zlib": "^1.0.5"
},
"dependencies": {
"axios": "^0.19.0",
"bootstrap": "^4.5.0",
"react": "^16.8.1",
"react-dom": "^16.8.1",
"react-lazy-load-image-component": "^1.5.1",
"react-paginate": "^6.5.0",
"react-redux": "^7.2.2",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"redux": "^4.0.5",
"redux-immutable-state-invariant": "^2.1.0",
"redux-thunk": "^2.3.0"
}
}

React js babel transform and minification in asp.net core

I have a asp.net core 2.0 application and I am using react.js also. I have some jsx files in that.
I want to minify those jsx files and then use. For js & css minification,
I defined rules in bundleconfig.json but wiring rules for jsx throws errors.
Can anyone help me how I can minify jsx in asp.net core application.
Update
Below is my project structure
below is webpack.config file
const path = require("path");
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const WebpackShellPlugin = require('webpack-shell-plugin');
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
process.traceDeprecation = true;
module.exports = {
entry: {
home: "./wwwroot/js/v2/userdefined/home.page.js"
},
output: {
path: path.resolve(__dirname, "wwwroot/dist"),
filename: "[name].js",
publicPath: "/dist/"
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: false,
extractComments: 'all',
uglifyOptions: {
compress: true,
output: null
}
}),
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
safe: true,
discardComments: {
removeAll: true,
},
},
})
]
},
plugins: [
new webpack.ContextReplacementPlugin(/\.\/locale$/, 'empty-module', false, /jsx$/),
new webpack.LoaderOptionsPlugin({
options: {}
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
Popper: ['popper.js', 'default']
}),
new CompressionPlugin({
test: /\.(js|css)/
}),
new UglifyJsPlugin(),
new WebpackShellPlugin({
onBuildStart: ['echo "Starting postcss command"'],
onBuildEnd: ['postcss --dir wwwroot/dist wwwroot/dist/*.css']
})
],
resolve: {
modules: [
path.resolve('./node_modules')
]
},
module: {
rules: [{
test: /\.scss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true
}
},
{
loader: "sass-loader"
}
]
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: ["babel-loader", "eslint-loader"]
},
{
test: /\.(jpe?g|png|gif)$/i,
loader: "file-loader"
},
{
test: /\.(woff|ttf|otf|eot|woff2|svg)$/i,
loader: "file-loader"
}
]
}
};
below is Gruntfile.js
/// <binding AfterBuild='cleanup' />
module.exports = function(grunt) {
require("jit-grunt")(grunt);
grunt.initConfig({
clean: ["./Modules/*"],
copy: {
main: {
expand: true,
src: [
"../Modules/**/bin/Debug/**/**/*.*",
"../Modules/**/wwwroot/**",
],
dest: "./Modules/"
},
css: {
expand: true,
cwd: "../Modules/AwesomeCMSCore.Modules.Frontend/wwwroot/dist",
src: ["cmscore.css"],
dest: "./wwwroot/dist/"
},
js: {
expand: true,
cwd: "../Modules/AwesomeCMSCore.Modules.Frontend/wwwroot/dist",
src: ["*.js"],
dest: "./wwwroot/dist/"
},
static: {
expand: true,
cwd: "../Modules/AwesomeCMSCore.Modules.Frontend/wwwroot/dist",
src: ["**"],
dest: "./wwwroot/dist/"
}
},
watch: {
css: {
files: ["../Modules/**/wwwroot/dist/*.css"],
tasks: ["copy:css"],
options: {
reload: true,
spawn: false
}
},
js: {
files: ["../Modules/**/wwwroot/dist/*.js"],
tasks: ["copy:js"],
options: {
reload: true,
spawn: false
}
}
}
});
grunt.registerTask("default", ["watch"]);
grunt.registerTask("cleanup", [
"clean",
"copy:main",
"copy:static"
]);
};
below is my package.json
{
"name": "ProjV2",
"version": "1.0.0",
"main": "index.js",
"author": "JitendraPancholi",
"license": "",
"scripts": {
"prod": "webpack -p --mode=production --config webpack.prod.js",
"start": "webpack --mode=development --config webpack.dev.js",
"lint:js": "eslint \"wwwroot/js/react/src/**/*.{js,jsx}\" --color",
"lint:style": "stylelint \"wwwroot/css/**/*.scss\" --syntax scss"
},
"devDependencies": {
"babel-cli": "6.26.0",
"babel-core": "6.26.3",
"babel-eslint": "8.2.6",
"babel-loader": "7.1.5",
"babel-plugin-transform-class-properties": "6.24.1",
"babel-plugin-transform-es2015-destructuring": "6.23.0",
"babel-plugin-transform-object-rest-spread": "6.26.0",
"babel-preset-es2015": "6.24.1",
"babel-preset-react": "6.24.1",
"babel-preset-stage-0": "6.24.1",
"compression-webpack-plugin": "1.1.11",
"css-loader": "1.0.0",
"cssnano": "^4.1.7",
"empty-module": "^0.0.2",
"eslint": "^5.0.0",
"eslint-loader": "2.0.0",
"eslint-plugin-react": "7.10.0",
"file-loader": "1.1.11",
"grunt": "1.0.3",
"grunt-contrib-clean": "1.1.0",
"grunt-contrib-copy": "1.0.0",
"grunt-contrib-watch": "1.1.0",
"jit-grunt": "0.10.0",
"jshint": "2.9.5",
"jshint-loader": "0.8.4",
"mini-css-extract-plugin": "^0.4.4",
"node-sass": "^4.11.0",
"optimize-css-assets-webpack-plugin": "^5.0.1",
"sass-loader": "7.0.3",
"style-loader": "0.21.0",
"stylelint": "9.3.0",
"stylelint-config-recommended": "2.1.0",
"stylelint-config-recommended-scss": "3.2.0",
"stylelint-config-standard": "18.2.0",
"stylelint-scss": "3.1.3",
"uglify-js": "^3.4.9",
"uglifyjs-webpack-plugin": "1.2.7",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-merge": "^4.2.1",
"webpack-shell-plugin": "^0.5.0"
},
"dependencies": {
"#aspnet/signalr": "^1.1.0",
"#tinymce/tinymce-react": "^2.2.5",
"axios": "^0.18.0",
"bootstrap": "^4.1.1",
"chart.js": "^2.7.2",
"font-awesome": "^4.7.0",
"jquery": "^3.3.1",
"moment": "^2.22.2",
"popper.js": "^1.14.1",
"prop-types": "^15.6.0",
"react": "^16.4.1",
"react-bootstrap-table": "^4.3.1",
"react-dom": "^16.4.1",
"react-select": "^1.2.1",
"react-values": "^0.2.4",
"reactstrap": "^6.3.0",
"toastr": "^2.1.4"
}
}
All my fils jsx files are as per below
You cant do that. React has to transform into js file in order to run in the browser
Normally you will need module bundle tool like webpack
You can view my full config here
Let me know if you need any more help
Update: Here is how I transform jsx into js
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: ["babel-loader", "eslint-loader"]
},

Using gulp/webpack and getting unexpected token error with spread operator

I have installed stage-2 which from the post I am seeing it should make this work. However when I build the project it is not working. I will add my:
.babelrc
webpack.config.js
gulpfile.js
package.json
to let you see what I am doing. Files will be in order.
{
"presets": ["es2015", "react", "stage-3", "stage-0", "stage-1", "stage-2", "env"],
"plugins": ["transform-object-rest-spread"]
}
var webpack = require('webpack');
var path = require('path');
var CommonsChunkPlugin = new require('webpack/lib/optimize/CommonsChunkPlugin');
var chunks = ['app'];
var config = require('./package.json');
module.exports = {
entry: {
app: './src/index.js'
},
output: {
path: __dirname + '/dist',
filename: 'bundle/[name].js',
sourceMapFilename: 'bundle/[name].map'
},
node: {
fs: 'empty'
},
devtool: '#source-map',
plugins:
process.env.NODE_ENV === 'production'
? [
new CommonsChunkPlugin({
name: 'commons',
chunks: chunks
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compress: {
warnings: false,
drop_console: true
}
})
]
: [
new CommonsChunkPlugin({
name: 'commons',
chunks: chunks
})
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'env', 'stage-2']
}
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.(jpg|png|svg)$/,
loader: 'file-loader',
query: {
name: '[name].[ext]',
outputPath: 'images/',
publicPath: config.server ? '/' : 'dist/',
useRelativePath: false
}
}
]
}
};
var gulp = require('gulp');
var minifyCSS = require('gulp-minify-css');
var autoprefixer = require('gulp-autoprefixer');
var gp_concat = require('gulp-concat');
var gp_rename = require('gulp-rename');
var gp_uglify = require('gulp-uglify');
var less = require('gulp-less');
var to5 = require('gulp-6to5');
var path = require('path');
gulp.task('less', function() {
return gulp
.src('./assets/style.less')
.pipe(
less({
paths: [path.join(__dirname, 'less', 'includes')]
})
)
.pipe(gulp.dest('./assets/css'));
});
gulp.task('css', ['less'], function() {
return gulp
.src([
'./assets/css/bootstrap.css',
'./assets/css/style.css',
'./assets/css/swiper.css',
'./assets/css/dark.css',
'./assets/css/font-icons.css',
'./assets/css/animate.css',
'./assets/css/magnific-popup.css',
'./assets/css/responsive.css',
'./assets/css/custom.css'
])
.pipe(minifyCSS())
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9'))
.pipe(gp_concat('style.min.css'))
.pipe(gulp.dest('./dist/css/'));
});
gulp.task('copy-fonts', function() {
return gulp.src(['./assets/css/fonts/**']).pipe(gulp.dest('./dist/css/fonts/'));
});
gulp.task('style', ['css', 'copy-fonts'], function() {});
gulp.task('js', function() {
return gulp
.src(['./assets/js/jquery.js', './assets/js/plugins.js', './assets/js/functions.js', './assets/js/custom.js'])
.pipe(gp_concat('vendor.min.js'))
.pipe(gulp.dest('./dist/js/'))
.pipe(gp_rename('vendor.min.js'))
.pipe(gp_uglify())
.pipe(gulp.dest('./dist/js/'));
});
gulp.task('es6-es5', ['js'], function() {
return gulp
.src(['./src/*/**.js', './src/*/*/**.js'])
.pipe(to5())
.pipe(gulp.dest('./dist/es5/'));
});
gulp.task('watch', function() {
gulp.watch(['./src/*/**.js', './src/*/*/**.js', './assets/js/**.js'], ['es6-es5']);
});
gulp.task('prod', ['style', 'es6-es5'], function() {});
gulp.task('default', ['es6-es5', 'watch'], function() {});
{
"name": "ghost-blog",
"version": "0.0.0",
"server": false,
"private": true,
"scripts": {
"dev": "concurrently \"webpack -w\" \"turbo devserver\"",
"clean": "rimraf ./dist/*",
"build": "npm run clean && set NODE_ENV=production && webpack && gulp prod",
"postinstall": "npm run build"
},
"dependencies": {
"babel-preset-env": "^1.6.1",
"babel-preset-stage-0": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"bluebird": "latest",
"body-parser": "latest",
"cheerio": "latest",
"concurrently": "^3.5.0",
"cookie-parser": "latest",
"debug": "latest",
"dotenv": "latest",
"file-loader": "latest",
"firebase": "latest",
"moment": "latest",
"react": "^16.0.0",
"react-bootstrap": "^0.31.3",
"react-dom": "latest",
"react-dropzone": "^4.2.0",
"react-player": "^0.25.2",
"react-redux": "latest",
"react-router-dom": "^4.2.2",
"react-time": "^4.3.0",
"redux": "latest",
"redux-thunk": "latest",
"stripe": "latest",
"superagent": "latest",
"sweetalert2": "^6.10.3",
"turbo360": "^1.4.69",
"webpack": "latest"
},
"devDependencies": {
"babel-core": "latest",
"babel-loader": "latest",
"babel-preset-es2015": "latest",
"babel-preset-react": "latest",
"json-loader": "latest",
"gulp": "latest",
"gulp-autoprefixer": "latest",
"gulp-6to5": "latest",
"gulp-concat": "latest",
"gulp-less": "latest",
"gulp-minify-css": "latest",
"gulp-rename": "latest",
"gulp-uglify": "latest",
"chai": "latest",
"chai-http": "latest",
"nodemon": "latest",
"mocha": "latest",
"mocha-jscs": "latest",
"mocha-jshint": "latest",
"rimraf": "latest"
},
"functions": {
"turbo360": "latest"
},
"babel": {
"presets": ["es2015", "react", "stage-2"]
},
"deploy": ["index.html", "dist"],
"app": "59e0c137221d130012ee41dc"
}
The stack trace shows that it is an error in Gulp, since the Webpack portion shows no errors. The issue is that you are using
var to5 = require('gulp-6to5');
which is not Babel at all, but the much older version of Babel called "6to5". If you change that to use gulp-babel and install that, things should work.
Given the config you've posted, you can trim down things to
{
"presets": ["env", "react", "stage-0"]
}
and with that config, you can also remove
query: {
presets: ['react', 'es2015', 'env', 'stage-2']
}
from your Webpack config since it's already in the .babelrc.
If object rest/spread is the only experimental feature you're planning to use, you can also do
{
"presets": ["env", "react"],
"plugins": ["transform-object-rest-spread"]
}

Karma mocha not recognizing JSX code

I am attempting to add automated testing to a react application using karma and mocha. The application is written using ES6 and JSX so I am also using webpack. I have imported the webpack config into the karma configuration settings, but I am still getting an error whenever I try to render a JSX component for testing:
Uncaught Error: Module parse failed: C:\Users\blahblahblah\app\tests\components\Clock.test.jsx Unexpected token (18:47)
You may need an appropriate loader to handle this file type.
| let testTime = 100;
| let expected = '00:01:40';
| let clock = TestUtils.renderIntoDocument(<Clock />);
| let actual = clock.formatTime(testTime);
|
at app/tests/components/Clock.test.jsx:74
Here are the files in question:
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const VENDOR_LIBS = [
'axios', 'react', 'react-dom',
'react-loading', 'react-router', 'moment'
];
module.exports = {
entry: {
bundle: [
'script-loader!jquery/dist/jquery.min.js',
'script-loader!foundation-sites/dist/js/foundation.min.js',
'./app/app.jsx',
], // compile app files to bundle.js
vendor: VENDOR_LIBS // compile vendor files to vendor.js
},
externals: {
jquery: 'jQuery'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].[chunkhash].js'
},
resolve: {
alias: {
appStyles: path.resolve(__dirname, 'app/styles/app.scss'),
Main: path.resolve(__dirname, 'app/components/Main.jsx'),
Nav: path.resolve(__dirname, 'app/components/Nav.jsx'),
Timer: path.resolve(__dirname, 'app/components/Timer.jsx'),
Countdown: path.resolve(__dirname, 'app/components/Countdown.jsx'),
Clock: path.resolve(__dirname, 'app/components/Clock.jsx'),
Controls: path.resolve(__dirname, 'app/components/Controls.jsx')
},
extensions: [".js", ".jsx"]
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.jsx?$/,
exclude: /node_modules/
},
{
use: ['style-loader', 'css-loader', 'sass-loader'],
test: /\.scss$/
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest']
}),
new HtmlWebpackPlugin({
template: './app/index.html'
}),
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery'
})
],
devtool: 'cheap-module-eval-source-map'
}
karma.conf.js
const webpackConfig = require('./webpack.config.js');
module.exports = (config) => {
config.set({
browsers: ['Chrome'],
singleRun: true,
frameworks: ['mocha'],
files: ['app/tests/**/*.test.jsx'],
preprocessors: {
'app/tests/**/*.test.jsx': ['webpack', 'sourcemap']
},
reporters: ['mocha'],
client: {
mocha: { // after 5 seconds, if a test hasnt finished, cancel it
timeout: '5000'
},
webpack: webpackConfig, // use our established webpack config
webpackServer: {
noInfo: true
}
}
})
}
package.json
{
"name": "boilerplate",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "karma start",
"clean": "rimraf dist",
"build": "SET NODE_ENV=production npm run clean & webpack -p",
"serve": "webpack-dev-server"
},
"author": "",
"license": "MIT",
"dependencies": {
"axios": "^0.16.1",
"express": "^4.15.2",
"moment": "^2.18.1",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-loading": "0.0.9",
"react-router": "^3.0.0"
},
"devDependencies": {
"babel-core": "^6.24.0",
"babel-loader": "^6.4.1",
"babel-preset-env": "^1.1.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.23.0",
"babel-preset-stage-0": "^6.24.1",
"colors": "^1.1.2",
"css-loader": "^0.28.1",
"expect": "^1.20.2",
"foundation-sites": "^6.3.1",
"html-webpack-plugin": "^2.28.0",
"jquery": "^3.2.1",
"karma": "^1.7.0",
"karma-chrome-launcher": "^2.1.1",
"karma-mocha": "^1.3.0",
"karma-mocha-reporter": "^2.2.3",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^2.0.3",
"mocha": "^3.4.1",
"node-sass": "^4.5.3",
"react-addons-test-utils": "^15.5.1",
"rimraf": "^2.6.1",
"sass-loader": "^6.0.5",
"script-loader": "^0.7.0",
"style-loader": "^0.17.0",
"webpack": "^2.3.3",
"webpack-dev-middleware": "^1.10.2",
"webpack-dev-server": "^2.4.5"
}
}
.babelrc
{
"presets": ["react", "es2015", "stage-0"]
}
The test that keeps failing:
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-dom/test-utils';
import expect from 'expect';
import $ from 'jQuery';
// Karma not recognizing webpack aliases
import Clock from 'babel-loader!./../../components/Clock.jsx';
describe('Clock Component', () => {
it('should exist', () => {
expect(Clock).toExist();
});
// THIS TEST KEEPS FAILING
describe('formatSeconds()', () => {
it('should format seconds to hh:mm:ss', () => {
let testTime = 100;
let expected = '00:01:40';
let clock = TestUtils.renderIntoDocument(<Clock />); // JSX = problem
let actual = clock.formatTime(testTime);
expect(actual).toBe(expected);
});
});
});

Unexpected token react-router in express server

{
"name": "shopping-cart-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "karma start",
"start": "node server.js"
},
"author": "",
"license": "MIT",
"dependencies": {
"axios": "^0.9.1",
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"body-parser": "^1.17.1",
"express": "^4.13.4",
"faker": "^4.1.0",
"marked": "^0.3.6",
"mongoose": "^4.9.6",
"nodemon": "^1.11.0",
"react": "^0.14.7",
"react-addons-test-utils": "^0.14.7",
"react-bootstrap": "^0.31.0",
"react-dom": "^0.14.7",
"react-router": "^2.0.0"
},
"devDependencies": {
"babel-core": "^6.5.1",
"babel-loader": "^6.2.2",
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"babel-preset-es2015": "^6.5.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0",
"css-loader": "^0.23.1",
"expect": "^1.14.0",
"foundation-sites": "6.2.0",
"jquery": "^2.2.1",
"karma": "^0.13.22",
"karma-chrome-launcher": "^0.2.2",
"karma-mocha": "^0.2.2",
"karma-mocha-reporter": "^2.0.0",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^1.7.0",
"mocha": "^2.4.5",
"node-sass": "^3.4.2",
"sass-loader": "^3.1.2",
"script-loader": "^0.6.1",
"style-loader": "^0.13.0",
"webpack": "^1.12.13"
}
}
I am trying to implement server side routing for a react app i am working on. I am using react-router for this purpose. Here is part of my server.js code
const renderToString = require ('react-dom/server');
let match, RouterContext = require('react-router');
const routes = require ('/app/router');
const React = require('react');
app.get('*', (req, res) => {
match(
{ routes, location: req.url },
(err, redirectLocation, renderProps) => {
// in case of error display the error message
if (err) {
return res.status(500).send(err.message);
}
// in case of redirect propagate the redirect to the browser
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
}
// generate the React markup for the current route
let markup;
if (renderProps) {
// if the current route matched we have renderProps
markup = renderToString(<RouterContext {...renderProps}/>);
} else {
// otherwise we can render a 404 page
markup = renderToString(<NotFoundPage/>);
res.status(404);
}
// render the index template with the embedded React markup
return res.render('index', { markup });
}
);
});
//my webpack config file
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: [
'script!jquery/dist/jquery.min.js',
'script!foundation-sites/dist/foundation.min.js',
'./app/app.jsx'
],
externals: {
jquery: 'jQuery'
},
plugins: [
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery'
})
],
output: {
path: __dirname,
filename: './public/bundle.js'
},
resolve: {
root: __dirname,
modulesDirectories: [
'node_modules',
'./app/components'
],
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0']
},
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/
}
]
},
sassLoader: {
includePaths: [
path.resolve(__dirname, './node_modules/foundation-sites/scss')
]
},
devtool: 'cheap-module-eval-source-map'
};
I get an unexpected token < at < RouterContext {...renderProps}/>.
I have looked over the tutorial am am working of off, but i am not so sure what i have done wrong. Any suggestion would be really appreciated
You are using the Babel presets react, es2015 and stage-0.
None of those presets includes the plugin you need to make the object spread syntax you are using work – this part of your code:
<RouterContext {...renderProps} />
You can fix your problem by adding the transform-object-rest-spread plugin to your Babel config like this:
module: {
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['transform-object-rest-spread']
},
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/
}
]
}
Don't forget to install the plugin using
npm install --save-dev babel-plugin-transform-object-rest-spread

Resources