5

I am new in reactjs. I am just start learning reactjs. I have problem using webpack in nodejs. I want to create node server which will run the webpack file. I have webpack file:

const {resolve} = require('path');
const webpack = require('webpack');
const validate = require('webpack-validator');
const {getIfUtils, removeEmpty} = require('webpack-config-utils');

module.exports = env => {
  const {ifProd, ifNotProd} = getIfUtils(env)

  return validate({
    entry: './index.js',
    context: __dirname,
    output: {
      path: resolve(__dirname, './build'),
      filename: 'bundle.js',
      publicPath: '/build/',
      pathinfo: ifNotProd(),
    },
    devtool: ifProd('source-map', 'eval'),
    devServer: {
      port: 8080,
      historyApiFallback: true
    },
    module: {
      loaders: [
        {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
        {test: /\.css$/, loader: 'style-loader!css-loader'},
        {test: /(\.eot|\.woff2|\.woff|\.ttf|\.svg)/, loader: 'file-loader'},
      ],
    },
    plugins: removeEmpty([
      ifProd(new webpack.optimize.DedupePlugin()),
      ifProd(new webpack.LoaderOptionsPlugin({
        minimize: true,
        debug: false,
        quiet: true,
      })),
      ifProd(new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: '"production"',
        },
      })),
      ifProd(new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          screw_ie8: true, // eslint-disable-line
          warnings: false,
        },
      })),
    ])
  });
};

How can i use this configuration with nodejs. please help

2
  • Webpack is a code bundler , it is made to work in development environment. The usual process of using webpack is to bundle all the files locally, and then when all files are prepared, deploy it to the server without webpack on the server side. Commented Aug 14, 2017 at 12:07
  • 1
    You are doing too much in the webpack.config.js file. Have your server point to another webpack file if in production, otherwise have it use the webpack.dev.config.js file. github.com/christian4423/express_blog in the app.js file shows a solid approach to this. Commented Nov 8, 2017 at 19:06

4 Answers 4

5
+25

First of all your webpack configuration will not run on webpack 2+, because webpack-validator is deprecated, so I have removed it. I would recommend you to install npm install webpack-dev-server -g globally and use it as a server in your react development. This is how you can modify your configuration to use it (webpack.config.js):

const path = require("path");
const webpack = require('webpack');
const {getIfUtils, removeEmpty} = require('webpack-config-utils');

module.exports = env => {
  const {ifProd, ifNotProd} = getIfUtils(env)

  return {
    entry: [
      "webpack-dev-server/client?http://localhost:3003",
      "webpack/hot/only-dev-server",
      "react-hot-loader/patch"
    ],
    context: __dirname,
    output: {
      path: path.join(__dirname, './build'),
      filename: 'bundle.js',
      publicPath: '/build/',
      pathinfo: ifNotProd(),
    },
    devtool: ifProd('source-map', 'eval'),
    devServer: {
        contentBase: path.join(__dirname, "src"),
        // enable HMR
        hot: true,
        // embed the webpack-dev-server runtime into the bundle
        inline: true,
        // serve index.html in place of 404 responses to allow HTML5 history
        historyApiFallback: true,
        port: 3003
    },
    module: {
      loaders: [
        {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
        {test: /\.css$/, loader: 'style-loader!css-loader'},
        {test: /(\.eot|\.woff2|\.woff|\.ttf|\.svg)/, loader: 'file-loader'},
      ],
    },
    plugins: removeEmpty([
    //...
    // same as before
    //...
    ])
  };
};

package.json :

{
  ...
  "dependencies": {},
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "react-hot-loader": "^3.1.1",
    "webpack": "^3.8.1",
    "webpack-config-utils": "^2.3.0",
    "webpack-dev-server": "^2.9.4",
  }
}

in the same folder where webpack.config.js is make one file webpack.development.js, that will just set enviorment:

var config = require('./webpack.config.js')

module.exports = config("development"); // can be "production" or "development"

Files structure:

root
    build
        bundle.js
    src
        index.html
    index.js
    package.json
    webpack.config.js
    webpack.development.js

At the end just run it: webpack-dev-server --config webpack.development.js --progress -p --hot -w

--hot - will run server, -w - watch files

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

Comments

2

My suggestion:

package.json scripts (install webpack (-g and –save-dev), nodemon (-g and –save-dev) and concurrently (–save-dev))

  "scripts": {
    "webpack-watch-client": "webpack -w",
    "server": "nodemon server",
    "dev": "concurrently --kill-others \"npm run webpack-watch-client\" \"npm run server\""
  }

webpack.config.js example

'use strict'

const path = require('path');

const PATHS = {
  app: path.join(__dirname, 'src'),
  public: path.join(__dirname, 'public')
};


module.exports = {
  entry: {
    app: PATHS.app,
  },
  output: {
    path: PATHS.public,
    filename: 'js/bundle.js'
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: ['react', 'es2015']
            }
          }
        ]
      },
      {
        test: /\.css$/,
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader' }
        ]
      },
      {
        test: /\.(woff|woff2|eot|ttf)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              outputPath: 'assets/fonts/'
            }
          }
        ]
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              outputPath: 'assets/img/'
            }
          }
        ]
      }
    ]
  },
 plugins: [
// plugins
  ]
};

Node server start point is ./server.js

React client start point is ./src/index.js

Output path ./public contain index.html with lines:

  <div id="root"></div>
  <script type="text/javascript" src="/js/bundle.js" charset="utf-8"></script>

Output path for bundle.js is ./public/js

Output path for fonts is ./public/assets/fonts

Output path for images is ./public/assets/img

Start: npm run dev (listening port is defined in server.js)

etc.

Comments

1

I don't know if this would help, but i think that you want do the other way round:

  1. Create your configuration un Webpack.config file (Webpack).
  2. Your webpack file lauch the Node server (Express).
  3. Your server return your font-end file (React).

You can learn some info about webpack in this post.

Comments

0

Try this. Save this code in webpackConfig.js

var webpack = require('webpack')

var config = require('./your_config')

var compiler = webpack(config)

compiler.run(function(err, stats){
   console.log(err, stats)
})

run with "node webpackConfig.js"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.