0

I'm trying to run my server.js file locally but every time I try "node server.js" I get a:

SyntaxError: Unexpected Identifier for "import React from react

I'm simply trying to see if I get a console.log("connected") message in a function that accesses my database.

I have already tried adding the "transform-es2015-modules-amd" to my plugins in the package.json file in the Babel section. I have tried almost every other solution offered on Stack Overflow posts similar to mine.

package.json

{
  "dependencies": {
    "atob": "^2.1.2",
    "axios": "^0.19.0",
    "babel-loader": "^8.0.0-beta.6",
    "babel-upgrade": "^1.0.1",
    "btoa": "^1.2.1",
    "concurrently": "^5.0.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql": "^2.17.1",
    "node-fetch": "^2.6.0",
    "react": "^16.11.0",
    "react-dom": "^16.11.0",
    "react-redux": "^7.1.1",
    "react-router": "^5.1.2",
    "react-router-dom": "^5.1.2",
    "redux": "^4.0.4",
    "request": "^2.88.0",
    "serialize-javascript": "^2.1.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.6.4",
    "@babel/core": "^7.6.4",
    "@babel/node": "^7.6.3",
    "@babel/preset-env": "^7.6.3",
    "@babel/preset-react": "^7.6.3",
    "@types/node": "^12.11.2",
    "babel-loader": "^8.0.6",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^3.2.0",
    "nodemon": "^1.19.4",
    "style-loader": "^1.0.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.9",
    "webpack-dev-server": "^3.9.0",
    "webpack-node-externals": "^1.7.2"
  },
  "babel": {
    "presets": [
      "@babel/preset-react",
      "@babel/preset-env"
    ]
  "plugins": [
      "transform-es2015-modules-amd"
    ]
  }
}                                                                                                                                                                                   

server.js

import React from 'react';
import { StaticRouter } from 'react-router-dom';
import { Provider as ReduxProvider } from "react-redux";

import App from '../client/src/App.js';
import { renderToString } from "react-dom/server";
import createStore, { initialize, fetchCharacters } from './store.js';

var path = require("path");
var express = require("express");
var serialize = require("serialize-javascript");
var db = require('./db');

const PORT = process.env.HTTP_PORT || 4001;
const app = express();
app.use('/static', express.static(path.join(__dirname, 'public')));
console.log(__dirname);

app.get('/*', function(req, res) {
  const context = {};
  const store = createStore();
  store.dispatch(initialize());

  Promise.all([store.dispatch(fetchCharacters())]).then(() => {
    const component = (
      <ReduxProvider store={store}>
        <StaticRouter location={req.url} context={context}>
          <App/>
        </StaticRouter>
      </ReduxProvider>
    );
    const ss_react = renderToString(component);
    const ss_state = store.getState();

    res.writeHead( 200, { "Content-Type": "text/html" });
    res.end(htmlTemplate(component, ss_state));
  });
});

function htmlTemplate(component, ss_state) {
    return `
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>React SSR</title>
        </head>

   `;
}

app.listen(PORT, () => {
    console.log(`server listening at port ${PORT}. `);
});

webpack.config.js

const webpack = require('webpack')
const nodeExternals = require('webpack-node-externals')
const path = require('path')

const js = {
  test: /\.m?(js|jsx)$/,
  exclude: /(node_modules|bower_components)/,
  use: {
    loader: 'babel-loader'
  }
}

const css = {
    test: /\.css$/,
    use: [
      "style-loader",
      {
        loader: "css-loader",
        options: {
          modules: true
        }
      }
    ]
}

const serverConfig = {
  mode: 'development',
  target: 'node',
  node: {
    __dirname: false
  },
  externals: [nodeExternals()],
  entry: {
    'index.js': path.resolve(__dirname, 'server/server.js')
  },
  module: {
    rules: [js]
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name]'
  }
}

const clientConfig = {
  mode: 'development',
  target: 'web',
  entry: {
    'index.js': path.resolve(__dirname, 'client/src/index.js')
  },
  module: {
    rules: [js, css]
  },
  optimization: {
    splitChunks: {
      chunks: 'all'
    }
  },
  output: {
    path: path.resolve(__dirname, 'dist/public'),
    filename: '[name]'
  }
}

module.exports = [serverConfig, clientConfig]

1
  • 1
    Run webpack, not the file itself Commented Nov 8, 2019 at 21:49

1 Answer 1

1

Node does not understand React JSX. That's what Webpack is for - it uses Babel to transpile your code into vanilla JavaScript.

Looks like you have webpack-dev-server as a dev dependency, so it should already be installed (if you've done an npm install). Make sure you have something like this in your package.json scripts field:

"scripts": {
  "start:dev": "webpack-dev-server --config webpack.config.js"
},

Then run npm run start:dev in your console.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked! Thank you! I had another compiler error but that was because I was missing a comma and it wasn't in proper JSON format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.