Ivonne Terrero
Ivonne Terrero

Reputation: 83

WebPack configuration- what is the proper code and what does it mean

I'm learning React and want to understand how web pack is configured for a project.

It would be great if someone can tell me what the following lines of code are doing.

const fs = require('fs')
const path = require('path')
const webpack = require('webpack')

function isDirectory(dir) {
  return fs.lstatSync(dir).isDirectory()
}

const SubjectsDir = path.join(__dirname, 'subjects')
const SubjectDirs = fs.readdirSync(SubjectsDir).filter(function (dir) {
  return isDirectory(path.join(SubjectsDir, dir))
})

module.exports = {
  devtool: 'source-map',

  entry: SubjectDirs.reduce(function (entries, dir) {
    if (fs.existsSync(path.join(SubjectsDir, dir, 'exercise.js')))
      entries[dir + '-exercise'] = path.join(SubjectsDir, dir, 'exercise.js')

    if (fs.existsSync(path.join(SubjectsDir, dir, 'solution.js')))
      entries[dir + '-solution'] = path.join(SubjectsDir, dir, 'solution.js')

    if (fs.existsSync(path.join(SubjectsDir, dir, 'lecture.js')))
      entries[dir + '-lecture'] = path.join(SubjectsDir, dir, 'lecture.js')

    return entries
  }, {
    shared: [ 'react', 'react-dom' ]
  }),

  output: {
    path: '__build__',
    filename: '[name].js',
    chunkFilename: '[id].chunk.js',
    publicPath: '__build__'
  },

  resolve: {
    extensions: [ '', '.js', '.css' ]
  },

  module: {
    loaders: [
      { test: /\.css$/, loader: 'style!css' },
      { test: /\.js$/, exclude: /node_modules|mocha-browser\.js/, loader: 'babel' },
      { test: /\.woff(2)?$/,   loader: 'url?limit=10000&mimetype=application/font-woff' },
      { test: /\.ttf$/, loader: 'file' },
      { test: /\.eot$/, loader: 'file' },
      { test: /\.svg$/, loader: 'file' },
      { test: require.resolve('jquery'), loader: 'expose?jQuery' }
    ]
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({ name: 'shared' })
  ],

  devServer: {
    quiet: false,
    noInfo: false,
    historyApiFallback: {
      rewrites: [
        { from: /ReduxDataFlow\/exercise.html/,
          to: 'ReduxDataFlow\/exercise.html'
        }
      ]
    },
    stats: {
      // Config for minimal console.log mess.
      assets: true,
      colors: true,
      version: true,
      hash: true,
      timings: true,
      chunks: false,
      chunkModules: false
    }
  }
}

This informaiton is coming from a training course, but they do not explain what the lines are doing.

Upvotes: 0

Views: 217

Answers (1)

prateekm33
prateekm33

Reputation: 111

Webpack is what we call a module bundler for JavaScript applications. You can do a whole slew of things with it that help a client browser download and run your code. In the case of React, it helps convert JSX code into plain JS so that the browser can understand it. JSX itself will not run in the browser. We can even use plugins to help minify code, inject HTML, bundle various groups of code together, etc. Now that the introduction to Webpack is out of the way, let's take a look at the code. I will be starting from the very top. Feel free to skip down to #3 if you are only interested in the Webpack configuration object.

  1. The following code will require the modules that are needed in this file. fs is short for "filesystem" and is a module that gives you functions to run that can access the project's filesystem. path is a common module used to resolve or create pathnames to files and is very easy to use! And then we have the webpack module through which we can access webpack specific functions (ie: webpack plugins like webpack.optimize.UglifyJsPlugin).

    const fs = require('fs')
    const path = require('path')
    const webpack = require('webpack')
    
  2. These next few lines first set up a helper function to determine whether or not something in the filesystem being read is a directory.

    function isDirectory(dir) {
      return fs.lstatSync(dir).isDirectory()
    }
    
    const SubjectsDir = path.join(__dirname, 'subjects')
    const SubjectDirs = fs.readdirSync(SubjectsDir).filter(function (dir) {
      return isDirectory(path.join(SubjectsDir, dir))
    })
    
  3. devtool specifies which developer tool you want to use to help with debugging. Options are listed here : https://webpack.github.io/docs/configuration.html#devtool. This can be very useful in helping you determine exactly which files and lines and columns errors are coming from.

    devtool: 'source-map'
    
  4. These next few lines tell Webpack where to begin bundling your files. These initial files are called entry points. The entry property in a Webpack configuration object should be an object whose keys determine the name of a bundle and values point to a relative path to the entry file or the name of a node_module. You can also pass in an array of files to each entry point. This will cause each of those files to be bundled together into one file under the name specified by the key - ie: react and react-dom will each be parsed and have their outputs bundled under the name shared.

    entry: SubjectDirs.reduce(function (entries, dir) {
      if (fs.existsSync(path.join(SubjectsDir, dir, 'exercise.js')))
        entries[dir + '-exercise'] = path.join(SubjectsDir, dir, 'exercise.js')
    
      if (fs.existsSync(path.join(SubjectsDir, dir, 'solution.js')))
        entries[dir + '-solution'] = path.join(SubjectsDir, dir, 'solution.js')
    
      if (fs.existsSync(path.join(SubjectsDir, dir, 'lecture.js')))
         entries[dir + '-lecture'] = path.join(SubjectsDir, dir, 'lecture.js')
    
      return entries
    }, {
      shared: [ 'react', 'react-dom' ]
    }),
    

    In the reduce function we simply read through the SubjectsDir, determine whether files exercise.js, lecture.js & solution.js exist, and then provide the path to those files as values associated with the key names identified by dir + '-' + filename (ie: myDir-exercise). This may end up looking like the following if only exercise.js exists:

    entry : {
      'myDir-exercise': 'subjectDir/myDir/exercise.js',
      share: ['react', 'react-dom']
    }
    
  5. After we provide entry points to the Webpack configuration object, we must specify where we want Webpack to output the result of bundling those files. This can be specified in the output property.

     output: {
      path: '__build__',
      filename: '[name].js',
      chunkFilename: '[id].chunk.js',
      publicPath: '__build__'
     },
    

    The path property defines the absolute path to the output directory. In this case we call it __build__.

    The filename property defines the output name of each entry point file. Webpack understands that by specifying '[name]' you are referring to the key you assigned to each entry point in the entry property (ie: shared or myDir-exercise).

    The chunkFilename property is similar to the filename property but for non-entry chunk files which can be specified by the CommonChunksPlugin (see below). The use of [id] is similar to the use of [name].

    The publicPath property defines the public URL to where your files are located, as in the URL from which to access your files through a browser.

  6. The resolve property tells Webpack what how to resolve your files if it can not find them for some reason. There are several properties we can pass here with extensions being one of them. The extensions property tells Webpack which file extensions to try on a file if one is not specified in your code.

     resolve: {
       extensions: [ '', '.js', '.css' ]
     },
    

    For example, let's say we have the following code

    const exercise = require('./exercise');
    

    We can leave out the .js because we have provided that string in the resolve property of the webpack configuration and Webpack will try and append .js to this at bundling time to find your file. As of Webpack 2 we also no longer need to specify an empty string as the first element of the resolve property.

  7. The module property tells Webpack how modules within our project will be treated. There are several properties we can add here and I suggest taking a look at the documentation for more details. loaders is a common property to use and with that we can tell Webpack how to parse particular file types within our project. The test property in each loader is simply a Regex that tells Webpack which files to run this loader on. This /\.js$/ for example will run the specified loader on files that end with .js. babel-loader is a widely used JavaScript + ES6 loader. The exclude property tells Webpack which files to not run with the specified loader. The loader property is the name of the loader. As of Webpack 2 we are no longer able to drop the -loader from the string as we see here.

  8. Plugins have a wide range of functions. As mentioned earlier we can use plugins to help minify code or to build chunks that are used across our entire application, like react and react-dom. Here we see the CommonChunksPlugin being used which will bundle the files under the entry name shared together as a chunk so that they can be separated from the rest of the application.

  9. Finally we have the devServer property which specifies certain configurations for the behavior of webpack-dev-server, which is a separate module from webpack. This module can be useful for development in that you can opt out of building your own web server and allow webpack-dev-server to serve your static files. It also does not write the outputs to your filesystem and serves the bundle from a location in memory at the path specified by the publicPath property in the output property of the Webpack configuration object (see #5). This helps make development faster. To use it you would simply run webpack-dev-server in place of webpack. Take a look at the documentation online for more details.

The configuration object that we've taken a look at follows the Webpack 1 standard. There are many changes between Webpack 1 and 2 in terms of configuration syntax that would be important to take a look at. The concepts are still the same, however. Take a look at the documentation for information on migrating to Webpack 2 and for further Webpack 2 details.

Upvotes: 2

Related Questions