My react app work fine in webpack-dev-server but production builds redirects to the page not found route. I have tried hashRouter too but it redirects to the homepage on every Route.
Please let me know what I am missing. I kind of new into this. Also, my build bundle is near about 2mbs. I tried some code splitting but that didn't worked.
Here is my webpack.config.js-
var path = require('path')
var webpack = require('webpack')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var CleanWebpackPlugin = require('clean-webpack-plugin')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const extractSass = new ExtractTextPlugin({
filename: "style.css",
});
module.exports = {
entry: {
main: './src/index.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js',
},
module: {
loaders: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
},
{
test: /\.s?css$/,
use: extractSass.extract({
use: [{
loader: "css-loader"
}, {
loader: "sass-loader"
}],
fallback: "style-loader"
})
},
{
test: /\.(eot|svg|ttf|woff(2)?)(\?v=\d+\.\d+\.\d+)?/,
loader: 'url-loader'
},
{
test: /\.html$/,
use: ['html-loader']
},
{
test: /\.(jpg|png)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/',
publicPath: ''
}
}
]
}
]
},
plugins:[
new CleanWebpackPlugin(['dist']),
extractSass,
new HtmlWebpackPlugin({
title: 'Caching',
template: 'index.html'
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
sequences: true,
dead_code: true,
conditionals: true,
booleans: true,
unused: true,
if_return: true,
join_vars: true,
drop_console: true
},
mangle: {
except: ['$super', '$', 'exports', 'require']
},
output: {
comments: false
}
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
]
};
package.json file.
{
"name": "react-afinoz",
"version": "1.0.0",
"description": "Afinoz Get best and cheap Loans in Delhi, Noida",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "npm run prod",
"build": "webpack-dev-server --content-base src/ --inline --hot --open --history-api-fallback",
"prod": "webpack -p --progress"
},
"author": "",
"license": "ISC",
"dependencies": {
"autoprefixer": "^7.1.6",
"aws-sdk": "^2.128.0",
"axios": "^0.16.2",
"node-sass": "^4.5.3",
"preload-webpack-plugin": "^2.0.0",
"react": "^15.6.1",
"react-cookies": "^0.1.0",
"react-document-meta": "^2.1.2",
"react-dom": "^15.6.1",
"react-materialize": "^1.0.16",
"react-router": "^4.1.2",
"react-router-dom": "^4.1.2",
"react-s3-uploader": "^4.5.0",
"script-ext-html-webpack-plugin": "^1.8.7",
"style-ext-html-webpack-plugin": "^3.4.3",
"url-loader": "^0.5.9"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^0.1.16",
"compression-webpack-plugin": "^1.0.1",
"css-loader": "^0.28.4",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^0.11.2",
"html-loader": "^0.5.1",
"html-webpack-plugin": "^2.30.1",
"node-sass": "^4.5.3",
"postcss-loader": "^2.0.8",
"sass-loader": "^6.0.6",
"style-loader": "^0.18.2",
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1",
"webpack-merge": "^4.1.0"
}
}
index.js file:-
import React from "react"
import ReactDOM from "react-dom"
import { BrowserRouter,browserHistory} from 'react-router-dom'
import App from "./routes.js"
import style from "./sass/style.scss"
const main = document.getElementById('main')
ReactDOM.render((
<BrowserRouter history={browserHistory}>
<App />
</BrowserRouter>
), main);
Router.js file:-
import React from "react"
import { Switch, Route } from 'react-router-dom'
import Home from "./home"
import Login from "./login"
import SignUp from "./signUp"
import NotFound from "./404.js"
export default class App extends React.Component{
render(){
return(
<Switch>
<Route exact path='/' component={Home}/>
<Route path='/login' component={Login}/>
<Route path='/signUp' component={SignUp}/>
<Route path="*" component={NotFound}/>
</Switch>
);
}
}
Here,try to use absolute path rather than relative
entry: {
main: path.join(__dirname, './src/app.tsx'),
}
Related
I am having difficulty with resolving webpack deployment issue.
In development mode everything seems fine, but as I deployed this project through vercel, I am only getting blank screen. When I checked the page, nothing but index.html existed. (no other js files)
These are my files below. I really want to know what on earth the problem is.
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ReactRefreshWebpackPlugin = require('#pmmmwh/react-refresh-webpack-plugin');
const { ESBuildMinifyPlugin } = require('esbuild-loader');
const isDevelopment = process.env.NODE_ENV !== 'production';
module.exports = () => ({
mode: isDevelopment ? 'development' : 'production',
devtool: isDevelopment ? 'eval-cheap-module-source-map' : false,
cache: { type: isDevelopment ? 'memory' : 'filesystem' },
entry: './src/index.tsx',
target: 'web',
output: {
filename: 'js/[name]-[chunkhash].js',
assetModuleFilename: 'img/[hash][ext][query]',
pathinfo: false,
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
clean: true,
},
resolve: {
alias: {
icons: path.resolve(__dirname, 'public/assets/icons'),
images: path.resolve(__dirname, 'public/assets/images'),
components: path.resolve(__dirname, 'src/components'),
data: path.resolve(__dirname, 'src/data'),
docs: path.resolve(__dirname, 'src/docs'),
pages: path.resolve(__dirname, 'src/pages'),
styles: path.resolve(__dirname, 'src/styles'),
types: path.resolve(__dirname, 'src/types'),
utils: path.resolve(__dirname, 'src/utils'),
},
extensions: ['*', '.js', '.tsx', '.ts'],
modules: [__dirname, 'src', 'node_modules'],
fallback: {
process: require.resolve('process/browser'),
zlib: require.resolve('browserify-zlib'),
stream: require.resolve('stream-browserify'),
util: require.resolve('util'),
buffer: require.resolve('buffer'),
assert: require.resolve('assert'),
},
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'esbuild-loader',
options: {
loader: 'tsx',
target: 'esnext',
},
},
{
test: /\.(png|jpg|svg|gif)$/,
type: 'asset/resource',
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(ts|tsx)$/,
exclude: '/node_modules',
use: 'ts-loader',
},
{
test: /restructure(\/|\\)src(\/|\\)[\w]+.js/,
use: [
{
loader: 'imports-loader',
options: {
type: 'commonjs',
imports: 'multiple ../../buffer/ Buffer Buffer',
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({ template: './public/index.html' }),
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
process: 'process/browser',
}),
new webpack.EnvironmentPlugin({
DEVELOPMENT: isDevelopment,
}),
isDevelopment && new webpack.HotModuleReplacementPlugin(),
isDevelopment && new ReactRefreshWebpackPlugin(),
],
optimization: {
minimize: !isDevelopment,
minimizer: [
new ESBuildMinifyPlugin({
target: 'esnext',
css: true,
}),
],
splitChunks: {
chunks: 'all',
},
},
externals: {
axios: 'axios',
},
devServer: {
port: 3000,
open: true,
hot: true,
historyApiFallback: true,
},
});
package.json
{
"name": "webpack",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"engines": {
"node": ">=16.15.0",
"yarn": ">=1.22.17"
},
"scripts": {
"build": "webpack",
"dev": "NODE_ENV=development & webpack serve --progress",
"build:dev": "NODE_ENV=development & yarn build",
"build:prod": "NODE_ENV=production & yarn build"
},
"keywords": [],
"devDependencies": {
"#pmmmwh/react-refresh-webpack-plugin": "^0.5.7",
"#react-pdf/types": "^2.1.0",
"#types/react": "^18.0.12",
"#types/react-dom": "^18.0.5",
"#types/shortid": "^0.0.29",
"#types/styled-components": "^5.1.25",
"#typescript-eslint/eslint-plugin": "^5.27.1",
"#typescript-eslint/parser": "^5.27.1",
"css-loader": "^6.7.1",
"esbuild-loader": "^2.19.0",
"eslint": "^8.17.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jsx-a11y": "^6.5.1",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react": "^7.30.0",
"eslint-plugin-react-hooks": "^4.5.0",
"eslint-plugin-simple-import-sort": "^7.0.0",
"html-webpack-plugin": "^5.5.0",
"imports-loader": "^4.0.0",
"lodash": "^4.17.21",
"prettier": "^2.6.2",
"react-refresh": "^0.13.0",
"style-loader": "^3.3.1",
"ts-loader": "^9.3.0",
"typescript": "^4.7.3",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.9.2"
},
"dependencies": {
"#react-pdf/renderer": "^2.2.0",
"assert": "^2.0.0",
"axios": "^0.27.2",
"browserify-zlib": "^0.2.0",
"buffer": "^6.0.3",
"node-env": "^0.1.6",
"process": "^0.11.10",
"react": "^18.1.0",
"react-daum-postcode": "^3.1.1",
"react-dom": "^18.1.0",
"react-router-dom": "^6.3.0",
"shortid": "^2.2.16",
"stream-browserify": "^3.0.0",
"styled-components": "^5.3.5",
"styled-reset": "^4.4.1",
"util": "^0.12.4"
}
}
index.tsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import GlobalFont from 'styles/globalFont';
import GlobalStyle from 'styles/globalStyle';
import App from './App';
const rootEl = document.getElementById('root');
if (!rootEl) throw new Error('Failed to find the root element');
const root = createRoot(rootEl);
root.render(
<React.StrictMode>
<GlobalFont />
<GlobalStyle />
<App />
</React.StrictMode>,
);
App.tsx
import Home from 'pages/Home';
import PdfViewer from 'pages/PdfViewer';
import Test from 'pages/Test';
import React from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/docs" element={<PdfViewer />} />
<Route path="/test" element={<Test />} />
</Routes>
</BrowserRouter>
);
}
export default App;
I'm building a module federation/react aplication. I'm currently working on my container, and i've been setting up the environment for everything, including TS, now, when i try to create my routes, only the Home appear, but other routes don't. Let me show you
This is how my Routing.tsx looks like
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Autenticacion from "./Website/Autenticacion";
import Home from "./Website/Home";
const Routing = () => {
return (
<div>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/auth" element={<Autenticacion />} />
</Routes>
</BrowserRouter>
</div>
);
};
export default Routing;
When i go to "/" the component appears with no problem
But, when i go "/auth"
Nothing appears and, no errors in the console, it's like "/[something]" does not work, i'm pretty sure this might be an stupid error, it's just that, i can't see it.
As i told you, i'm using webpack for module federation, and, i don't know if this problem is related to that configuration.
What is going on ?
UPDATING
This is my package.json
{
"name": "container",
"version": "1.0.0",
"main": "index.tsx",
"license": "MIT",
"scripts": {
"start": "webpack serve --config config/webpack.dev.js"
},
"dependencies": {
"#emotion/react": "^11.7.0",
"#emotion/styled": "^11.6.0",
"#mui/icons-material": "^5.2.0",
"#mui/material": "^5.2.2",
"#mui/styles": "^5.2.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.0.2"
},
"devDependencies": {
"#babel/core": "^7.16.0",
"#babel/plugin-transform-runtime": "^7.16.4",
"#babel/preset-env": "^7.16.4",
"#babel/preset-react": "^7.16.0",
"#babel/preset-typescript": "^7.16.0",
"#types/node": "^16.11.10",
"#types/react": "^17.0.37",
"#types/react-dom": "^17.0.11",
"#types/react-router-dom": "^5.3.2",
"#types/webpack": "^5.28.0",
"babel-loader": "^8.2.3",
"clean-webpack-plugin": "^4.0.0",
"css-loader": "^6.5.1",
"html-webpack-plugin": "^5.5.0",
"style-loader": "^3.3.1",
"typescript": "^4.5.2",
"webpack": "^5.64.4",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.6.0",
"webpack-merge": "^5.8.0"
}
}
This is my config in webpack, maybe you can spot an error related to this.
webpack.common
module.exports = {
entry: "./src/index.tsx",
module: {
rules: [
{
test: /\.m?tsx$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: [
["#babel/preset-react", { runtime: "automatic" }],
"#babel/preset-env",
"#babel/preset-typescript",
],
plugins: ["#babel/plugin-transform-runtime"],
},
},
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
},
};
webpack.dev
const { merge } = require("webpack-merge");
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const commonConfig = require("./webpack.common");
const { dependencies } = require("../package.json");
const devConfig = {
mode: "development",
devServer: {
port: 3000,
historyApiFallback: {
index: "index.html",
},
},
plugins: [
new ModuleFederationPlugin({
name: "container",
remotes: {},
shared: dependencies,
}),
new HtmlWebpackPlugin({
template: "./public/index.html",
}),
],
};
module.exports = merge(commonConfig, devConfig);
Another Update
This is my index.tsx file (I have to do it like this)
import("./bootstap");
export {};
This is my bootstrap file
import { render } from "react-dom";
import { CssBaseline } from "#mui/material";
import Routing from "./Routing";
render(
<>
<CssBaseline />
<Routing />
</>,
document.getElementById("root")
);
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>
);
}
}
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 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