{
"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
Related
Since im building my webapp with React, when i try to set something into an undefined object property, the code processing crashes (reproducible with breakpoint debugging) and no errors are shown in the console log. Also the chrome react extension does not give me any errors.
So to finding a bug is more time consuming that it should be.
let changedJsonResponse = jsonResponse;
changedJsonResponse.data = newTableData; // changedJsonResponse.data is undefined
// throws no error & code proccess crashes
webpack.config.js
const webpack = require('webpack');
const path = require('path');
let config = {
devtool: 'eval-source-map',
entry: {
FooManagement: ['babel-polyfill', './domains/FooManagement/entry.jsx'],
},
output: {
path: path.resolve(__dirname, '../web/react/'),
filename: '[name].js'
},
externals: {
'jquery': 'window.jQuery',
'bootbox': 'window.bootbox',
},
resolve: {
alias: {
alias_shared: path.resolve(__dirname, 'shared'),
},
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: [/node_modules/],
loader: 'babel-loader',
options: {presets: ['es2015', 'react']}
},
{
test: /\.css/,
loader: 'style-loader!css-loader'
}
]
}
};
module.exports = config;
package.json
{
"author": "myself",
"version": "0.0.1",
"description": "",
"main": "index.jsx",
"scripts": {
"watch": "webpack -d --watch",
"build": "webpack -p"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-polyfill": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.7",
"style-loader": "^0.19.0",
"webpack": "^3.8.1"
},
"dependencies": {
"axios": "^0.16.2",
"dateformat": "^3.0.2",
"is-uuid": "^1.0.2",
"lodash": "^4.17.4",
"react": "^16.0.0",
"react-cropper": "^1.0.1",
"react-dom": "^16.0.0",
"react-dropzone": "^4.2.3",
"react-router-dom": "^4.2.2",
"react-switchery-component": "0.0.7",
"uuid": "^3.1.0"
}
}
Chrome version: 62.0.3202.94
I was able to catch those errors in Axios .catch.
After a while i found the cause of the problem.
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);
});
});
});
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..
I have been trying out React with Webpack and Redux and stumbled upon an
Uncaught SyntaxError: Unexpected token import.
I know that there is a lot of questions like these, but I have find none that involves Redux.
Here is my webpack config:
var app_root = 'src'; // the app root folder: src, src_users, etc
var path = require('path');
var CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
app_root: app_root, // the app root folder, needed by the other webpack
configs
entry: [
// http://gaearon.github.io/react-hot-loader/getstarted/
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'babel-polyfill',
__dirname + '/' + app_root + '/index.js',
],
output: {
path: __dirname + '/public/js',
publicPath: 'js/',
filename: 'bundle.js',
},
module: {
loaders: [
{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
exclude: /node_modules/,
},
{
// https://github.com/jtangelder/sass-loader
test: /\.scss$/,
loaders: ['style', 'css', 'sass'],
},
{
test: /\.css$/,
loaders: ['style', 'css'],
}
],
},
devServer: {
contentBase: __dirname + '/public',
},
plugins: [
new CleanWebpackPlugin(['css/main.css', 'js/bundle.js'], {
root: __dirname + '/public',
verbose: true,
dry: false, // true for simulation
}),
],
};
index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore} from 'redux';
// importera App komponenten
import App from './components/App';
// importera stylesheet
import './stylesheets/main.scss';
//importera reducer
import { reducers } from './reducers/index';
import Provider from "react-redux/src/components/Provider";
// skapa users-list, tomt objekt
let users = [];
for (let i = 1; i < 10; i++) {
// fyller objektet med användare med dessa villkor
users.push({
id: i,
username: 'Andreas' + i,
job: 'leethacker' + i,
});
const initialState = {
users: users,
}
}
// skapa Store
const store = createStore(reducers, initialState);
// skriver sedan ut denna komponent, render är Reacts funktion för att
skriva ut
ReactDOM.render(
<Provider store ={store}>
<App/>
</Provider> , document.getElementById('App'));
Package.json file:
{
"name": "redux-minimal",
"version": "1.0.0",
"description": "Start building complex react-redux apps today, with
this minimalist easy to understand starter kit (boilerplate)",
"keywords": [
"react",
"redux",
"minimal",
"starter kit",
"boilerplate"
],
"main": "index.js",
"homepage": "http://redux-minimal.js.org/",
"repository": {
"type": "git",
"url": "https://github.com/catalin-luntraru/redux-minimal"
},
"scripts": {
"start": "webpack-dev-server --inline --hot --history-api-fallback --
host localhost --port 8080",
"build-dev": "webpack --config webpack.dev.config.js",
"build-prod": "webpack -p --config webpack.prod.config.js",
"test": "mocha --recursive --compilers js:babel-register --require
babel-polyfill --require ignore-styles",
"test-watch": "npm test -- --watch"
},
"babel": {
"presets": [
"es2015",
"react",
"stage-3"
]
},
"author": "Catalin Luntraru",
"license": "MIT",
"dependencies": {
"react": "^15.4.2",
"react-bootstrap": "^0.30.7",
"react-dom": "^15.4.2",
"react-redux": "^5.0.2",
"react-router": "^3.0.1",
"react-router-bootstrap": "^0.23.1",
"react-router-redux": "^4.0.7",
"redux": "^3.6.0",
"redux-form": "^6.4.3",
"redux-saga": "^0.14.3"
},
"devDependencies": {
"babel-core": "^6.21.0",
"babel-loader": "^6.2.10",
"babel-polyfill": "^6.20.0",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-3": "^6.17.0",
"babel-runtime": "^6.20.0",
"clean-webpack-plugin": "^0.1.15",
"css-loader": "^0.26.1",
"enzyme": "^2.7.0",
"extract-text-webpack-plugin": "^1.0.1",
"ignore-styles": "^5.0.1",
"mocha": "^3.2.0",
"node-sass": "^4.3.0",
"react-addons-test-utils": "^15.4.2",
"react-hot-loader": "^1.3.1",
"redux-freeze": "^0.1.5",
"sass-loader": "^4.1.1",
"style-loader": "^0.13.1",
"webpack": "^1.14.0",
"webpack-dev-server": "^1.16.2",
"whatwg-fetch": "^2.0.1"
}
}
The error line that I see is indicative of a error that is not being transpiled correct by babel.
See this please,
"unexpected token import" in Nodejs5 and babel?
Also, please add the index.js entry file, package.json to be more informative.
Hope this helps!
The error is in webpack.config.js ,as the babel loader is not included properly in config file.change your code as :
module: {
loaders: [
{ test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['react', 'es2015']
}
},
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();