Categories
Uncategorized

Bootstrap4 default style does not appetite? Teach you to use NPM + Webpack + SASS to customize

Bootstrap is a popular front end style library, you can easily and quickly build applications, but the default style may is unsatisfactory, this article describes how to use NPM, Webpack, SASS source code to customize it for your own theme. Version using Bootstrap v4.3.1.

This article provides a way to use this template to prepare a background management Dunwoo Admin, the end of the text there are ways to obtain the source code. Demo: https: //dunwoo.com/projects/dunwoo-admin

Install Node.js

Webpack is a front-end tools and resources to package compiled, it depends on Node.js, at first describes how to configure and install green version of the Node.js.

Download green version: https: //nodejs.org/en/download/ (to node-v10.16.1-win-x64.zip for example)

And extract to a directory, such as D: \ node-v10.16.1, then set system environment variables:

NODE_HOME=D:\node-v10.16.1
NODE_PATH=%NODE_HOME%\node_modules
path=增加;%NODE_HOME%;

In the new home directory Node.js node_cache node_global and two directories, using the following command set npm global position of the mounting module and download cache path:

npm config set prefix "D:\node-v10.16.1\node_global"
npm config set cache "D:\node-v10.16.1\node_cache"

Finally, you can use the node -v and npm -v verify that the installation was successful at the command line.

Webpack Installation and Configuration

Before installing Webpack, need to use npm init generated in the project root directory package.json file, which is similar to Java, Maven’s pom.xml, used to describe the project meta-information, name, version, etc., more importantly, it specifies the project run-dependent module, the following is the project contents of this file:

{
  "name": "dunwoo-admin",
  "version": "1.0.0",
  "description": "Bootstrap 4 Theme",
  "author": "wskwbog",
  "license": "MIT",
  "private": true,
  "keywords": [],
  "scripts": {
    "build": "webpack --progress --colors",
    "dev": "webpack-dev-server --inline --devtool eval-source-map --progress",
    "start": "npm run dev"
  },
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/plugin-proposal-object-rest-spread": "^7.3.2",
    "@babel/preset-env": "^7.3.1",
    "autoprefixer": "^9.4.7",
    "babel-loader": "^8.0.6",
    "css-loader": "^3.2.0",
    "node-sass": "^4.12.0",
    "postcss-loader": "^3.0.0",
    "sass-loader": "^7.2.0",
    "style-loader": "^1.0.0",
    "webpack": "^4.39.2",
    "webpack-cli": "^3.3.7",
    "webpack-dev-server": "^3.8.0",
    "mini-css-extract-plugin": "^0.8.0",
    "clean-webpack-plugin": "^3.0.0"
  },
  "dependencies": {
    "bootstrap": "^4.3.1",
    "jquery": "^3.3.1",
    "popper.js": "^1.14.7"
  }
}

The key configuration in which the meaning is:

    scripts: script commands to configure the different functions of abbreviations can be used npm run build | dev easy call

    Module specified project development needed: devDependencies

    dependencies: Specifies the operation of the project depends module

Package.json can be configured after node_modules will be downloaded to the current directory in the current directory, run npm install dependent modules.

Before you start using Webpack, but also some configuration, which is more troublesome areas, webpack.config.js the project configuration as follows:

// 引入 node 相关模块
const path = require('path');

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
  mode: 'development',
  devtool: 'source-map',
  entry: {
    theme: './src/js/theme.js' // 入口文件
  },
  output: { // 打包输出目录
    path: path.resolve(__dirname, './dist/'),
    filename: 'js/[name].js'
  },
  devServer: { // 本地开发服务器
    contentBase: './dist/',
    host: '0.0.0.0',
    port: 3000,
    writeToDisk: true
  },
  module: {
    rules: [{
      test: /(\.jsx|\.js)$/, // 正则匹配 .jsx 或 .js 后缀的文件
      loader: 'babel-loader',
      exclude: /node_modules/
    }, {
      test: /\.(scss)$/, // 正则匹配 .scss 后缀的文件
      use: [{
        // loader: 'style-loader', // inject CSS to page
        loader: MiniCssExtractPlugin.loader,
        options: {
          // publicPath: '../',
          // hmr: process.env.NODE_ENV === 'development',
        },
      }, {
        loader: 'css-loader', // translates CSS into CommonJS modules
      }, {
        loader: 'postcss-loader', // Run postcss actions
        options: {
          plugins: function () { // postcss plugins, can be exported to postcss.config.js
            return [
              require('autoprefixer')
            ];
          }
        }
      }, {
        loader: 'sass-loader' // compiles Sass to CSS
      }]
    }]
  },
  plugins: [
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns:['js/*', 'css/*']
    }),
    new MiniCssExtractPlugin({
      filename: 'css/[name].css',
      chunkFilename: 'css/[id].css',
    })
  ]
}

Then analyze the role of the configuration items.

entry/output

entry: {
  theme: './src/js/theme.js'
},
output: {
  path: path.resolve(__dirname, './dist/'),
  filename: 'js/[name].js'
},

Entrance (entry) and exit (output) configuration is relatively simple, which specifies the building from the beginning of the output destination module and compile the results. ** __ dirname ** which represents the directory webpack.config.js located.

webpack-dev-server

Usual development process is:

    Modify scss style

    Then run the command-line compiler run build npm

    Finally, refresh the page to see results

This fully automated steps, Webpack provides a local development Web server webpack-dev-server, it can monitor changes to the code and automatically compile and publish basic configuration is as follows:

devServer: {
  contentBase: './dist/', // 资源根目录
  host: '127.0.0.1', // 绑定主机 IP 
  port: 3000, // 监听端口
  writeToDisk: true // 将编译结果写到磁盘
},

For more configuration items may refer to: https: //webpack.js.org/configuration/dev-server/

The next step is to configure Webpack two important concepts, Loader and Plugin:

    Loader: Compile and conversion module source code, such as the scss compiled into css, ES6 into the JS, the JSX files into JS files, etc.

    Plugin: Loader for solving function can not be achieved, such as cleaning, packaging optimization and compression, etc.

Babel

Bootstrap 4 ES6 use JS to rewrite all the components, while Babel is a JavaScript compiler, which can be used ES6 paper prepared grammar, turn into a browser compatible JS file. Package.json modules associated with it are as follows:

    @ Babel / core: Babel compiled kernel

    @ Babel / preset-env: preset for each environment Babel

  • babel-loader: 结合使用 Babel 和 webpack 编译 JavaScript
  • @ Babel / plugin-proposal-object-rest-spread: Support ES6 Extended operator (…)

And it is usually related to the configuration file into a file called .babelrc.js in:

module.exports = {
  presets: [
    [
      '@babel/env',
      {
        loose: true,
        modules: false,
        exclude: ['transform-typeof-symbol']
      }
    ]
  ],
  plugins: [
    '@babel/plugin-proposal-object-rest-spread'
  ]
};

CSS module

Webpack provides two Loader to handle style, css-loader and style-loader, two different tasks handled:

    css-loader: parsing @import and URL () method, to achieve a similar import / require () function

    style-loader: The pattern is added to the page, in combination with css-loader can be embedded into the JS file after the style of packaging in webpack

Sass CSS preprocessor for example native CSS is extended, the added characteristic variables, functions, etc., so that preparation of a more flexible css, Webpack configuration can be used directly after the following two Loader:

    sass-loader: The scss compiled into css

    postcss-loader: mainly used autoprefixer add browser prefixes

Specific configuration can be viewed webpack.config.js above, one thing should be noted that: high version of autoprefixer, supported browsers are usually placed .browserslistrc configuration file.

mini-css-extract-plugin

CSS will be extracted as separate plug-in file, create a CSS file for each file contains CSS, JS, and CSS support SourceMaps of demand loading, rely more than 4 version Webpack.

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // 指定资源路径, 默认与 webpackOptions.output 相等
              publicPath: '../',
              // 模块热加载相关配置
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
        ],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // all options are optional
      filename: '[name].css',
      chunkFilename: '[id].css',
      ignoreOrder: false, // Enable to remove warnings about conflicting order
    }),
  ],
};

For more configuration items may refer to: https: //webpack.js.org/plugins/mini-css-extract-plugin/

clean-webpack-plugin

Before Webpack building used to remove and clean up the build plugins folder, this plugin has a property cleanOnceBeforeBuildPatterns can configure which files and folders you want to delete, which does not remove, a simple example is as follows:

const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
    plugins: [
      new CleanWebpackPlugin({ // 只清理 js 和 css 目录中的文件
        cleanOnceBeforeBuildPatterns:['js/*', 'css/*']
      }),
    ],
};

For more configuration items may refer to: https: //www.npmjs.com/package/clean-webpack-plugin

Bootstrap Theme custom method

Bootstrap 4 custom theme in two ways, one is to directly modify the source code, but this is not good follow-up upgrade; the second is to modify SCSS variables it provides the flexibility to customize, so that no intrusive to the source, can be completely without touching the core files Bootstrap 4 of redesigned style. The basic structure of the project file is as follows:

dunwoo-admin/
├── .babelrc.js
├── .browserslistrc
├── .gitignore
├── package.json
├── webpack.config.js
├── README.md
├── src/
│   ├── scss/
│   │   ├── base/
│   │   ├── pages/
│   │   ├── partials/
│   │   ├── utilities/
│   │   ├── vendor/
│   │   └── _theme.scss
│   ├── js/
│   │   ├── modules/
│   │   ├── vendor/
│   │   └── theme.js
│   │── fonts/
│   └── img/
└── dist/
    ├── css/
    │   └── theme.css
    ├── js/
    │   └── theme.js
    ├── img/
    ├── fonts/
    └── libs/

Chief among these is the Sass file src / scss / _theme.scss:

@charset "utf-8";
// 覆盖原设计样式的变量
@import "base/variables-theme";
// bootstrap 核心源码
@import "../../node_modules/bootstrap/scss/bootstrap";
// 自定义组件的样式
@import "base/variables";
@import "base/general";

@import "partials/menubar";
@import "partials/navbar";
@import "partials/card";
@import "partials/widget";
@import "partials/timeline";

@import "pages/signin";

@import "utilities/utilities";

A simple modification of variable color theme is:

$theme-colors: (
  "primary":    #2c7be5,
  "secondary":  #95aac9,
  "success":    #00d97e,
  "info":       #39afd1,
  "warning":    #f6c343,
  "danger":     #e63757,
  "light":      #f8f9fa,
  "dark":       #3b506c
);

Execution npm run build in the root directory of the project will be able to see the changes in the results page.

summary

This article simply use webpack, for front-end is also currently studying, if wrong welcome that exchange.

Source code can be downloaded from GitHub link, https: //github.com/dwosc/dunwoo-admin

Or concern micro-channel public number “epiphany source” reply keyword “Bootstrap” get Baidu network disk download link.

Theme will be constantly updated optimization, welcome attention!

Leave a Reply