前端自动化工具使用

webpack服务和热更新

2019-08-06  本文已影响1人  小人物的秘密花园

参考

webpack-dev-server

webpack-dev-server简述

webpack-dev-server功能:
提供简单的web服务器以及热更新;

配置

1.创建本地项目webpack-demo

mkdir webpack-demo
cd webpack-demo

2.在webpack-demo的根目录下创建package.json文件

npm init -y
  1. 安装webpack依赖包
npm i webpack webpack-cli webpack-dev-server --save-dev

模块说明:

4.修改package.json文件的scripts属性值,进行打包资源的配置

"scripts": {
    "dev": "webpack-dev-server --open --mode development",
    "build": "webpack --mode production"
  },

5.安装webpack-dev-server

npm install --save-dev webpack-dev-server

6.在webpack.config.js文件中进行相关配置

const path = require('path');
// 显示进程的完成进度
var ProgressBarPlugin = require('progress-bar-webpack-plugin');
// 设置进度字体颜色
const chalk = require('chalk');
// 输出html
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  mode: 'development',
  entry: {
    app: './src/app.js'
  },
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name].[hash].js'
  },
  devServer: {
    baseContent: path.resolve(__dirname, '../dist'),// 静态资源根目录
    host: 'localhost',//服务器IP地址,默认是localhsot
    port: 5527,//服务监听的端口号
    compress: true,// 是否开启服务端压缩(gzip)
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: [
          {loader: 'babel-loader'}
        ]
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: 'style-loader',
            options: {
              singleton: true,// 单独的style
            }
          },
          {
            loader: 'css-loader'
          },
          {
            loader: 'postcss-loader'
          }
        ]
      },
      {
        test: /\.less$/,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader'
          },
          {
            loader: 'less-loader'
          }
        ]
      },
      {
        test: /\.scss$/,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader'
          },
          {
            loader: 'postcss-loader'
          },
          {
            loader: 'sass-loader'
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Webpack Study Demo',
      filename: 'index.html',//指定生成的HTML文件名
      template: path.join(__dirname, '../public/index.html') // 指定模板路径
    }),
    new ProgressBarPlugin({
      format: chalk.green('Progressing') + '[:bar]' + chalk.green(':percent') + '(:elapsed seconds)',
      clear: false
    })
  ]
}

7.运行命令

npm run dev
上一篇下一篇

猜你喜欢

热点阅读