Webpack large Bundle Size - reactjs

I am facing issue due to large webpack bundle size.
The size of my bundle size is nearby 166 kb. I am running webpack with -p flag. Most of the size is due to bundling of react module in my bundle file. So, what I am trying to do is that I am making two bundles: one which contain my app specific code and the other one which contains minified version of the npm which do not change frequently.
My bundle size is now 20 Kb.
Here is my webpack config file :
var path = require('path');
var webpack = require("webpack");
var node_modules_dir = path.resolve(__dirname, 'node_modules');
var config = {
entry: path.resolve(__dirname, 'index.js'),
output: getOutput(),
plugins: [
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
],
devtool: process.env.NODE_ENV === 'production' ? false : "eval",
module: {
loaders: [
{
test: /\.scss$/,
include: /src/,
loaders: [
'style',
'css',
'autoprefixer?browsers=last 3 versions',
'sass?outputStyle=expanded'
]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'url?limit=8192',
'img'
]
},
{
test: /\.jsx?$/,
exclude: (node_modules_dir),
loaders: [
'react-hot',
'babel-loader?presets[]=stage-0,presets[]=react,presets[]=es2015',
]
}, {
test: /\.css$/,
loader: 'style-loader!css-loader'
}
]
}
};
module.exports = config;
function getOutput() {
if (process.env.NODE_ENV === 'production') {
return {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
} else {
return {
publicPath: 'http://localhost:3000/',
filename: 'dist/bundle.js'
}
}
}
and here is my code :
import {connect, Provider} from 'react-redux';
import React from "react"
import {createStore, combineReducers} from 'redux';
import reducers from "./reducers";
import {increment} from "./actions/App.js";
var store = createStore(
combineReducers({
...reducers
})
);
class App extends React.Component {
render() {
return <div>
<span>Value is : {this.props.value}</span>
<div onClick={this.props.increment}><span>Increment</span></div>
</div>
}
}
App = connect((state)=> {
return {value: state.app.value}
}, {increment})(App);
module.exports = React.createClass({
render: ()=> {
return <Provider store={store}><App /></Provider>
}
});
and here is my package.json file
{
"name": "Sample App",
"version": "0.0.1",
"private": true,
"scripts": {
"webpack-server": "webpack-dev-server --hot --progress --colors --port 3000",
"serve-web": "npm run webpack-server",
"deploy": "NODE_ENV=production webpack -p --optimize-minimize"
},
"dependencies": {
"babel-core": "6.9.0",
"babel-loader": "6.2.4",
"babel-plugin-transform-runtime": "6.9.0",
"babel-preset-es2015": "6.9.0",
"babel-preset-react": "6.5.0",
"babel-preset-stage-0": "6.5.0",
"babel-relay-plugin": "^0.9.1",
"babel-runtime": "6.9.0",
"css-loader": "^0.23.0",
"file-loader": "^0.8.5",
"http-server": "^0.8.0",
"img-loader": "^1.3.1",
"node-fetch": "^1.5.3",
"postcss-loader": "^0.8.0",
"react": "15.3.2",
"react-dom": "^15.1.0",
"react-hot-loader": "^1.2.8",
"react-redux": "^4.4.5",
"redux": "^3.6.0",
"source-map-loader": "^0.1.5",
"url-loader": "^0.5.7",
"webpack": "1.13.1",
"webpack-dev-server": "1.14.1"
},
"jest": {
"preset": "jest-react-native"
},
"devDependencies": {
"babel-cli": "6.9.0",
"babel-core": "^6.9.0",
"babel-loader": "^6.2.4"
},
"engines": {
"npm": ">=3"
}
}
So, I have changed
module.exports = require('./lib/React');
to
module.exports = window.React;
in react.js file of react module as other npm like redux is also using react npm.
Is it a good thing to apply this patch in react.js file of react npm?
Is it a good thing to make two bundles like this?

You can use source map explorer to detect what is the problem.
https://www.npmjs.com/package/source-map-explorer

Related

React & Webpack 4 - lazy loading - can't get to generate chunk files

I am hoping someone can direct me on this issue. I am trying to setup lazy loading with react 16 & webpack 4. I followed the guides and duplicated the .babelrc, webpack config files to match the other examples where this is working. However i can't get chunk files to be generated with my project.
I am also running an express server (api) and launch both webpack dev server and express server from using nodemon:
"scripts": {
"start": "node index.js",
"server": "nodemon index.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
Here is the output when webpack is compiling bundle.js.
i 「wds」: 404s will fallback to /index.html
i 「wdm」: wait until bundle finished: /
i 「wdm」: Hash: a0bec46949ac77f6330c
Version: webpack 4.12.0
Time: 2782ms
Built at: 2018-09-05 22:59:39
Asset Size Chunks Chunk Names
bundle.js 4.01 MiB main [emitted] main
index.html 577 bytes [emitted]
Entrypoint main = bundle.js
Here is my .babelrc config:
{
"presets": [
[
"env",
{
"targets": {
"browsers": ["> 1%", "last 2 versions"]
}
}
],
"stage-2",
"react"
],
"plugins": ["syntax-dynamic-import", "transform-class-properties"]
}
Here is the webpack.config.js
const path = require('path');
const autoprefixer = require('autoprefixer');
const HtmlWebpacPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
chunkFilename: '[id].chunk.js',
publicPath: ''
},
resolve: {
extensions: ['.js', 'jsx']
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.css/,
exclude: /node_modules/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: true,
localIdentName: '[name]__[local]__[hash:base64:5]'
}
},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: () => [
autoprefixer({
browsers: ['> 1%', 'last 2 versions']
})
]
}
}
]
},
{
test: /\.(png|jpe?g|gif)$/,
loader: 'url-loader?limit=8000&name=images/[name].[ext]'
}
]
},
plugins: [
new HtmlWebpacPlugin({
template: __dirname + '/src/index.html',
filename: 'index.html',
inject: 'body'
})
],
devServer: {
historyApiFallback: true,
proxy: {
'/api': 'http://localhost:4000'
}
}
};
Package.json
{
"name": "react_webpack_starter",
"version": "1.0.0",
"description": "Boilerplate React & Webpac",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --mode development --open --hot --port 3000",
"build": "webpack --mode production"
},
"license": "ISC",
"dependencies": {
"axios": "^0.18.0",
"jwt-decode": "^2.2.0",
"moment": "^2.22.2",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-moment": "^0.7.7",
"react-redux": "^5.0.7",
"react-router-dom": "^4.3.1",
"redux": "^4.0.0",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"autoprefixer": "^9.1.5",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "^0.28.11",
"file-loader": "^1.1.11",
"html-webpack-plugin": "^3.2.0",
"postcss-loader": "^3.0.0",
"style-loader": "^0.21.0",
"url-loader": "^1.1.1",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
},
"proxy": "http://localhost:4000"
}
Async Component
import React, { Component } from 'react';
const asyncComponent = importComponent => {
return class extends Component {
state = {
component: null
};
componentDidMount() {
importComponent().then(cmp => {
this.setState({ component: cmp.default });
});
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
};
};
export default asyncComponent;
Code snippet
import asyncComponent from './HOC/asyncComponent';
const asyncTest = asyncComponent(() => {
return import('./Auth/Signup/Signup');
});
class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div className={styles.container}>
<Switch>
<Route path="/test" component={asyncTest} />
<Route path="/test2" component={asyncTest} />
<Route path="/test3" component={asyncTest} />
<Route path="/test4" component={asyncTest} />
</Switch>
</div>
</Router>
</Provider>
);
}
}

NPM Self Published Component cannot be found when using it in a React Project

I created my own React component and published it for use.
I just finished minifying for distribution and routing that through webpack.
(Babel used to just transpile and copy all files to dist).
however I now can't seem to import it for my projects anymore.
I install like:
npm i react-subreddit-posts
and then import like:
import SubredditPosts from 'react-subreddit-posts';
And then get this error:
Module not found: Can't resolve 'react-subreddit-posts'
so I must be exporting the module wrong or minifying it wrong???
Here is the source code:
import React, { Component } from 'react';
import ListContainer from './ListContainer';
import ListItemComponent from './ListItemComponent';
const redditAPI = 'https://www.reddit.com/r/';
export default class SubredditPosts extends Component {
constructor(props) {
super(props);
this.state = {
redditPosts: [],
isLoading: true
};
}
componentDidMount() {
const uri = `${redditAPI}${this.props.subreddit}.json`;
fetch(uri)
.then(data => data.json())
.then(this.handlePosts)
.catch(err => console.error(err));
}
handlePosts = (posts) => {
const apiPosts = posts.data.children.map((post, index) => {
return {
key: index,
title: post.data.title,
media: this.getMediaFromPost(post),
link: post.data.url
};
});
this.setState({
redditPosts: apiPosts,
isLoading: false
});
}
getMediaFromPost = (post) => {
const extension = post.data.url.split('.').pop();
if (post.data.hasOwnProperty('preview') && !extension.includes('gif')) {
return post.data.preview.images[0].source.url;
}
//do not use includes! because of Imgur's gifv links are not embeddable
if (extension === 'gif' || extension.includes('jpg') || extension.includes('jpeg')) {
return post.data.url;
}
//if can't load media then place placeholder
return this.props.placeholder;
}
render() {
return(
<ListContainer display={this.props.display}>
{ !this.state.isLoading && this.state.redditPosts.map(post => (
<ListItemComponent
display={this.props.display}
key={post.key}
link={post.link}
media={post.media}
title={post.title}
height={this.props.height}
width={this.props.width}
/>
))}
</ListContainer>
);
}
}
Here is what is in node_modules after install through npm:
I can export it just fine from the src, but not when it's published and distributed!
Package.json:
{
"name": "react-subreddit-posts",
"version": "1.0.12",
"description": "React component for displaying subreddit posts in different styles",
"main": "dist/main.js",
"repository": {
"type": "git",
"url": "https://github.com/stcalica/react-subreddit-posts"
},
"directories": {
"example": "example"
},
"scripts": {
"test": "jest",
"start": "webpack-dev-server --mode development",
"transpile": "rm -rf dist && webpack",
"prepublishOnly": "npm run transpile",
"compile": "webpack --config ./webpack.config.js --progress"
},
"jest": {
"setupTestFrameworkScriptFile": "./test/setupTest.js"
},
"keywords": [
"react",
"reddit"
],
"author": "Kyle Calica",
"license": "ISC",
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-jest": "^23.0.1",
"babel-loader": "^7.1.4",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-es2015-arrow-functions": "^6.22.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.11",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"html-webpack-plugin": "^3.2.0",
"jest": "^23.1.0",
"react": "^16.4.0",
"react-dom": "^16.4.0",
"react-test-renderer": "^16.4.1",
"style-loader": "^0.21.0",
"uglifyjs-webpack-plugin": "^1.2.5",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {}
}
webpack.config.js
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// const htmlWebpackPlugin = new HtmlWebpackPlugin({
// template: path.join(__dirname, 'example/src/index.html'),
// filename: './index.html'
// });
module.exports = {
entry: path.join(__dirname, 'example/src/index.js'),
output: {
libraryTarget: 'commonjs2',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['react'],
plugins: ['transform-class-properties']
}
}
]
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
// plugins: [ htmlWebpackPlugin ],
resolve: {
extensions: ['.js', '.jsx']
},
devServer: {
port: 3001
}
};
In your github I saw that you have the dist path in your .gitignore file but if you see your package.json you would see that your repo is pointing to the dist/index.js file which does not exist because you added it to the .gitignore.
Try:
Remove the exclusion in your gitignore
Recompile your app and create the dist folder
Publish it again in npm
Re-download your dependency by npm/yarn install
And make sure you got the latest version of your dependency

React minified copy error on production site

I keep getting a React minification warning when opening up my application.
I setup my webpack, package.json and redux store to settings that I thought would disable this warning, but it is still appearing.
Any help would be appreciated. I am copying over the code from my webpack, package.json and redux store. I am hosting my application on heroku.
Store
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers/root_reducer';
const middlewares = [thunk];
if (process.env.NODE_ENV !== 'production') {
const logger = require('redux-logger');
middlewares.push(logger.createLogger());
}
const configureStore = (preloadedState = {}) => (
createStore(
rootReducer,
preloadedState,
applyMiddleware(...middlewares)
)
);
export default configureStore;
Webpack
var path = require('path');
var webpack = require("webpack");
var plugins = [];
var devPlugins = [];
var prodPlugins = [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: true
}
})
];
plugins = plugins.concat(
process.env.NODE_ENV === 'production' ? prodPlugins : devPlugins
)
module.exports = {
entry: './frontend/gym_bump.jsx',
output: {
path: path.resolve(__dirname, 'app', 'assets', 'javascripts'),
filename: './bundle.js',
},
module: {
loaders: [
{
test: [/\.jsx?$/],
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
devtool: 'source-map',
resolve: {
extensions: ['.js', '.jsx', '*']
}
};
package.json
"dependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"chart.js": "^2.6.0",
"jquery": "^3.2.1",
"moment": "^2.18.1",
"react": "^15.6.1",
"react-chartjs-2": "^2.6.1",
"react-dom": "^15.6.1",
"react-infinite-scroll-component": "^2.4.0",
"react-redux": "^5.0.6",
"react-router-dom": "^4.1.2",
"react-simple-charts": "0.0.19",
"redux": "^3.7.2",
"redux-thunk": "^2.2.0",
"salad-ui": "^1.1.50",
"time-input": "^1.5.1",
"webpack": "^3.5.5",
"webpack-uglify-js-plugin": "^1.1.9"
},
"description": "This README would normally document whatever steps are necessary to get the application up and running.",
"version": "1.0.0",
"main": "index.js",
"directories": {
"doc": "docs",
"lib": "lib",
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"webpack": "webpack --watch",
"postinstall": "webpack"
},
"engines": {
"node": "8.2.1",
"npm": "5.3.0"
},
"devDependencies": {
"bundle-collapser": "^1.3.0",
"envify": "^4.1.0",
"uglify-js": "^3.0.28",
"uglify-js-brunch": "^2.10.0",
"uglifyify": "^4.0.3",
"redux-logger": "^3.0.6"
}
}
I fixed this, silly mistake. I was missing plugins: plugins, in my webpack.
module.exports = {
entry: './frontend/gym_bump.jsx',
output: {
path: path.resolve(__dirname, 'app', 'assets', 'javascripts'),
filename: './bundle.js',
},
**plugins: plugins,**
module: {
loaders: [
{
test: [/\.jsx?$/],
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
devtool: 'source-map',
resolve: {
extensions: ['.js', '.jsx', '*']
}
};

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);
});
});
});

Webpack - Uncaught SyntaxError: Unexpected token import with Redux

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']
}
},

Resources