Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Setting Up React Scaffolding with Webpack

Tech Aug 17 18

1. Review of Vue CLI Versions

Vue CLI provides scaffolding tools for project creation, tied to specific Webpack versions:

  • Vue CLI 4: Install via npm install -g @vue/cli (uses Webpack 4).
  • Vue CLI 3: Install via npm install -g @vue/cli@3 (uses Webpack 4).
  • Vue CLI 2: Install via npm install -g vue-cli (uses Webpack 3).

Project Creation Commands:

  • Vue CLI 3+/4: vue create my-app (scaffolds with Webpack 4).
  • Vue CLI 2: vue init webpack my-app (scaffolds with Webpack 3).
  • For backward compatibility (use Vue CLI 3/4 to create Vue 2-style projects), install @vue/cli-init:
    npm install -g @vue/cli-init
    
    Then run:
    vue init webpack my-app
    

In 2017, Vue CLI 2 (Webpack 3) used vue init webpack my-app. In 2018, Vue CLI 3 (Webpack 4) used vue create my-app. The new CLI supports legacy project creation via @vue/cli-init. The key difference between Vue CLI 2 and 3 is the underlying Webpack version: Webpack 3 (CLI 2) requires explicit configuration, while Webpack 4 (CLI 3/4) is "zero-config" but customizable.

Vue’s scaffolding uses Webpack 4 with zero configuration, while React’s scaffolding (e.g., create-react-app) is Webpack-based but pre-configured.

2. Webpack 3 Configuration

Webpack is a module bundler for JavaScript applications, originally built for React. For Webpack 3, configuration is done in webpack.config.js.

2.1 Create webpack.config.js

module.exports = {};

2.2 Entry File: src/main.js

console.log('Hello Webpack!');

2.3 Configure Entry

Define the antry point (e.g., app):

module.exports = {
  entry: {
    app: './src/main.js', // Bundles into app.js
  },
};

2.4 Configure Output

Specify the output directory and filename:

const path = require('path');

module.exports = {
  entry: { app: './src/main.js' },
  output: {
    path: path.resolve(__dirname, 'dist'), // Output to dist/
    filename: '[name].js', // Uses entry name (e.g., app.js)
  },
};

2.5 HTML Webpack Plugin (Auto-Inject JS)

To auto-generate index.html and inject bundled JS:

  1. Install dependencies:

    npm install webpack@3 html-webpack-plugin --save-dev
    
  2. Update webpack.config.js:

    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      entry: { app: './src/main.js' },
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
      },
      plugins: [
        new HtmlWebpackPlugin({
          template: 'index.html', // Uses root index.html as template
        }),
      ],
    };
    

Running webpack will generate dist/index.html with the bundled JS injected.

2.6 Minify JS with UglifyJS

Add the UglifyJsPlugin to minify JS:

  1. Update webpack.config.js:
    const webpack = require('webpack');
    
    module.exports = {
      // ...entry/output...
      plugins: [
        new webpack.optimize.UglifyJsPlugin(), // Minifies JS
        new HtmlWebpackPlugin({ template: 'index.html' }),
      ],
    };
    

3. CSS Modules with Loaders

To import CSS in JavaScript, use style-loader and css-loader.

3.1 Create src/main.css

html {
  background-color: #f66;
}

3.2 Import CSS in src/main.js

import './main.css';
console.log('Hello Webpack!');

3.3 Install Loaders

npm install style-loader css-loader@0 --save-dev

3.4 Configure CSS Loaders

Update webpack.config.js:

module.exports = {
  // ...entry/output...
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'], // Process from right to left
      },
    ],
  },
  plugins: [/* ... */],
};

4. SCSS Module Support

Use sass-loader, node-sass for SCSS.

4.1 Install Dependencies

npm install node-sass sass-loader@7 --save-dev

4.2 Create src/main.scss

html {
  background: #00f;
}

4.3 Import SCSS in src/main.js

import './main.scss';
console.log('Hello Webpack!');

4.4 Configure SCSS Loader

Update webpack.config.js rules:

module: {
  rules: [
    { test: /\.css$/, use: ['style-loader', 'css-loader'] },
    {
      test: /\.scss$/,
      use: ['style-loader', 'css-loader', 'sass-loader'],
    },
  ],
},

5. LESS Module Support

Use less and less-loader.

5.1 Install Dependencies

npm install less less-loader --save-dev

5.2 Create src/main.less

html {
  background: #0f0;
}

5.3 Import LESS in src/main.js

import './main.less';
console.log('Hello Webpack!');

5.4 Configure LESS Loader

Update webpack.config.js rules:

module: {
  rules: [
    // ...CSS, SCSS rules...
    {
      test: /\.less$/,
      use: ['style-loader', 'css-loader', 'less-loader'],
    },
  ],
},

6. Stylus Module Supporrt

Use stylus and stylus-loader.

6.1 Install Dependencies

npm install stylus stylus-loader --save-dev

6.2 Create src/main.stylus

html
  background: #000

6.3 Import Stylus in src/main.js

import './main.stylus';
console.log('Hello Webpack!');

6.4 Configure Stylus Loader

Update webpack.config.js rules:

module: {
  rules: [
    // ...CSS, SCSS, LESS rules...
    {
      test: /\.stylus$/,
      use: ['style-loader', 'css-loader', 'stylus-loader'],
    },
  ],
},

7. JavaScript Transpilation with Babel

To transpile modern JavaScript (ES6+) to ES5, use Babel.

7.1 Install Dependencies

npm install babel-core@6 babel-loader@7 --save-dev
npm install babel-preset-es2015 babel-preset-env babel-preset-react --save-dev

7.2 Create .babelrc

{
  "presets": ["es2015", "env", "react"]
}

7.3 Configure Babel Loader

Update webpack.config.js rules:

module: {
  rules: [
    // ...CSS, SCSS, LESS, Stylus rules...
    {
      test: /\.js$/,
      exclude: /node_modules/,
      use: 'babel-loader',
    },
  ],
},

8. Media and Font File Handling

Use file-loader and url-loader for images, fonts, and media.

8.1 Install Dependencies

npm install file-loader url-loader --save-dev

8.2 Configure Loaders

Update webpack.config.js rules:

module: {
  rules: [
    // ...other rules...
    {
      test: /\.(png|jpg|gif|svg)$/,
      use: {
        loader: 'url-loader',
        options: {
          limit: 10000, // Inline if <10KB, else use file-loader
          name: 'static/images/[name].[hash:7].[ext]',
        },
      },
    },
    {
      test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)$/,
      use: {
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: 'static/media/[name].[hash:7].[ext]',
        },
      },
    },
    {
      test: /\.(woff|woff2|eot|ttf|otf)$/,
      use: {
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: 'static/fonts/[name].[hash:7].[ext]',
        },
      },
    },
  ],
},

9. Webpack Dev Server

A development server with hot reloading.

9.1 Install Dependencies

npm install webpack-dev-server@2 --save-dev

9.2 Run the Server

webpack-dev-server

9.3 Configure Dev Server (Proxy for CORS)

Update webpack.config.js with devServer:

module.exports = {
  // ...entry, output, module...
  devServer: {
    host: '0.0.0.0', // Accessible via LAN
    port: 8080,
    proxy: {
      '/api': {
        target: 'http://47.92.152.70',
        changeOrigin: true,
        pathRewrite: { '^/api': '' },
      },
    },
  },
};

9.4 Request Data with Axios

Install axios:

npm install axios --save

Update src/main.js:

import axios from 'axios';

axios.get('/api/pro').then((res) => {
  console.log(res.data);
});

10. NPM Scripts

Add scripts to package.json:

{
  "scripts": {
    "dev": "webpack-dev-server",
    "build": "webpack"
  }
}

11. Alias Configuration

Use @ as an alias for src:

const path = require('path');

module.exports = {
  // ...entry, output, module...
  resolve: {
    extensions: ['.js', '.vue', '.jsx'],
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
};

12. Webpack + Vue

To use Vue with Webpack:

12.1 Install Dependencies

npm install vue --save
npm install vue-loader@14 vue-template-compiler --save-dev

12.2 Configure Vue Loader

Update webpack.config.js rules:

module: {
  rules: [
    // ...other rules...
    {
      test: /\.vue$/,
      use: 'vue-loader',
    },
  ],
},
resolve: {
  alias: {
    '@': path.resolve(__dirname, 'src'),
    'vue$': 'vue/dist/vue.esm.js', // For runtime + compiler
  },
},

13. React Setup

Install React:

npm install react react-dom --save

Update src/main.js to render a React component:

import React from 'react';
import ReactDOM from 'react-dom';

const App = () => <h1>Hello React!</h1>;

ReactDOM.render(<App />, document.getElementById('root'));

14. Environment Variables

Use cross-env to set environment variables:

14.1 Install cross-env

npm install cross-env --save-dev

14.2 Update package.json Scripts

{
  "scripts": {
    "dev": "cross-env NODE_ENV=development webpack-dev-server",
    "build": "cross-env NODE_ENV=production webpack"
  }
}

14.3 Update Webpack Configuration

const isDev = process.env.NODE_ENV === 'development';

module.exports = {
  // ...
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(isDev ? 'development' : 'production'),
    }),
    // ...other plugins...
  ],
};
Tags: React

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.