Giter Site home page Giter Site logo

isomorphic-javascript-web-development's Introduction

Isomorphic JavaScript Web Development

This is the code repository for Isomorphic JavaScript Web Development, published by Packt. It contains all the supporting project files necessary to work through the book from start to finish.

About the Book

The latest trend in web development, Isomorphic JavaScript, allows developers to overcome some of the shortcomings of single-page applications by running the same code on the server as well as on the client. Leading this trend is React, which, when coupled with Node, allows developers to build JavaScript apps that are much faster and more SEO-friendly than single-page applications.

Instructions and Navigations

All of the codes are organized as per the chapters, each folder has the codes related to that chapter or appendix.
For example: Isomorphic-JavaScript-Web-Development/Chapter 04/4-browsersync/components/App.js

The code will look like the following:

  constructor(props) {
    super(props);
    this.state = { time: null };
  }

Related Products

isomorphic-javascript-web-development's People

Contributors

dominicpereira92 avatar packt-itservice avatar prashantmishrapackt avatar tomasalabes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

isomorphic-javascript-web-development's Issues

Code in chapter 4 not matching content in book

The package.json is not reflecting the content in the book, e.g.

"webpack-dev-middleware": "github:koistya/Webpack-dev-middleware",
"webpack-hot-middleware": "^2.21.0"

is missing and github:koistya/Webpack-dev-middleware is also not running with

"webpack": "^3.5.6",

which is referenced in the book.

Couldn't get it running as it is in the book, wondering if I should continue working on the examples if such obvious errors are in there.

window is not defined

If you pass a component that matches a URL in the renderToString() function, an error occurs that there is no window object. How do I solve this?

  • server.js
const express = require('express');
const path = require('path');
import React from 'react';
import ReactDOMServer from 'react-dom/server';

const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const config = require('../webpack.config.js');
const compiler = webpack(config);

import Router from '../routes/index'; // 라우터

import App from '../src/App';
import Html from "../src/Html";

const expressApp = express();
const port = process.env.PORT || 3000;

if (process.env.NODE_ENV != 'production') {
    expressApp.use(webpackDevMiddleware(compiler, {
        publicPath: '/'
    }));
}
expressApp.use(express.static(path.join(__dirname, '')));

expressApp.get('*', (request, response) => {

    console.log('request.. in express');
    console.log(Router.match(request));
    const component = ReactDOMServer.renderToString(Router.match(request));

    // const app = ReactDOMServer.renderToString(<App/>); // App 컴포넌트를 HTML 문자열로 랜더링
    const html = ReactDOMServer.renderToStaticMarkup(<Html
        title="Sample Title"
        description="Isomorphic web application sample"
        body={component}
    />);

    response.send(`<!DOCTYPE html>` + html);

});


expressApp.listen(port, () => {
    console.log(`App is listening at http://localhost:${port}/`);
});

  • App.js
import React, {useState, useEffect} from 'react';
import moment from "moment";
import Header from "./components/header/Header";
import Footer from "./components/footer/Footer";

export default function App() {

    const [time, setTime] = useState(null);

    useEffect(() => {
        console.log('use effect..');
        setTime(moment().format('hh:mm:ss a'));
    }, []);

    return (
        <div style={{height:'100%'}}>
            <Header/>
            <div style={{height:'100%'}}>
                <h1>Sample App</h1>
                <p>Current time is {time}</p>
            </div>
            <Footer/>
        </div>
    )

}

  • Header.js
import React from 'react';

export default function Header() {

    function goPage(path) {
        console.log(`goPage..`);
        console.log(window.location); // error
        // window.location = path;
    }

    return (
        <header style={{width: '100%', border: '1px dotted black'}}>
            <div>
                <span style={{padding: '4px'}}>My App |</span>
                <span style={{padding: '4px', cursor: 'pointer'}}>Home</span>
                <span style={{padding: '4px', cursor: 'pointer'}} onClick={goPage('/about')}>About</span>
            </div>
        </header>
    )
}

  • Router
import React from 'react';

import App from "../src/App";
import NotFound from "../src/components/error/NotFound";
import Error from "../src/components/error/Error";
import About from "../src/components/about/About";

const routes = [
    {name : 'home', path : '/', action : () => <App/>},
    {name : 'about', path : '/about', action : () => <About/>},
    {name : '404', path : '/404', action : () => <NotFound/>},
    {name : '500', path : '/500', action : () => <Error/>},
];


export default {
    match(location) {
        console.log(location.path);
        const route = routes.find(x => x.path === location.path);

        if (route) {
            try {
                return route.action();
            } catch (err) {
                console.log('err');
                return routes.find(x => x.path === '/500').action();
            }
        } else {
            console.log('404');
            return routes.find(x => x.path === '/404').action();
        }
    }
}
  • chater 2 code (Home.js)
/*
 * Learning Isomorphic Web Application Development
 * Copyright © 2016 Konstantin Tarkus, Packt Publishing
 */

import React, { Component } from 'react';
import Layout from '../../components/Layout';
import Hero from './Hero';

const path = '/';
const action = () => <Layout hero={<Hero />}><Home /></Layout>;

class Home extends Component {
  handleClick(event) {
    event.preventDefault();
    console.log(location);
    // window.location = event.currentTarget.pathname;
  }
  render() {
    return (
      <div>
        <h2>Popular things to rent</h2>
        <div>
          <a href="/s/Tools" onClick={this.handleClick}>
            <span>Tools</span>
          </a>
          <a href="/s/Books" onClick={this.handleClick}>
            <span>Books</span>
          </a>
          ...
        </div>
      </div>
    );
  }
}

export default { path, action };

Here, even if you access the location object, there is no error.

image

I have a question about the basic isomorphic router implementation.

image

ReferenceError: location is not defined

How should I handle this error?
I want to know how this error occurs because my code and example code are different.

import React from 'react';

export default function Header() {

    function goPage(path) {
        console.log(location); // error
        // window.location = path;
    }

    return (
        <header style={{width: '100%', border: '1px dotted black'}}>
            <div>
                <span style={{padding: '4px'}}>My App |</span>
                <span style={{padding: '4px', cursor: 'pointer'}}>Home</span>
                <span style={{padding: '4px', cursor: 'pointer'}} onClick={goPage('/about')}>About</span>
            </div>
        </header>
    )
}

my code : https://github.com/katanazero86/isomorphic-web

serve/build not working

I cloned the code of the repo and when I try to run npm run serve it cannot find the build/server.js file. Maybe a faulty build script? Also, the copying task doesn't finish, it just says 'starting copy' and then just spits out undefined.

Is it possible to request a code implemented in the latest version?

hi?

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode production --config ./webpack.server.js && webpack --mode production",
    "serve": "nodemon --exec babel-node server.js",
    "start": "npm run build && node ./build/server.js"
 },
"dependencies": {
    "@babel/polyfill": "^7.10.1",
    "bluebird": "^3.7.2",
    "express": "^4.17.1",
    "moment": "^2.26.0",
    "react": "^16.13.1",
    "react-dom": "^16.13.1"
  },
  "devDependencies": {
    "@babel/core": "^7.10.1",
    "@babel/node": "^7.10.1",
    "@babel/preset-env": "^7.10.1",
    "@babel/preset-react": "^7.10.1",
    "@babel/register": "^7.10.1",
    "babel-loader": "^8.1.0",
    "clean-webpack-plugin": "^3.0.0",
    "copy-webpack-plugin": "^6.0.1",
    "html-webpack-plugin": "^4.3.0",
    "mini-css-extract-plugin": "^0.9.0",
    "nodemon": "^2.0.4",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.11.0"
  }

I am currently trying to configure the same type app with webpack4 version and babel7 version.
But is it normal because I am struggling? I was left with this doubt and left this request.
And even in the existing code, " Uncaught SyntaxError: Unexpected token '<' " How do I resolve this error?

my code : https://github.com/katanazero86/isomorphic-web

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.