自动化构建工具WebPack

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自动化构建工具WebPack相关的知识,希望对你有一定的参考价值。

Webpack中文文档:https://www.webpackjs.com/

什么是 Webpack?

webpack 是一个模块打包器。webpack 的主要目标是将 javascript 文件打包在一起,打包后的文件用于在浏览器中使用,但它也能够胜任转换(transform)、打包(bundle)或包裹(package)任何资源(resource or asset)。

安装 Webpack

# 全局安装
npm install webpack -g
# 局部安装
npm install webpack --save-dev

由于webpack1.x和3.x版本存在区别,全局安装webpack以后,再局部安装可以避免版本冲突或不合适的情况

Webpack 打包js文件

    # webpack 原始js文件路径 打包后存放js文件路径
    webpack src/js/entry.js dist/js/bundle.js

Webpack 的配置文件webpack.config.js

const path = require(‘path‘);

module.exports = {
  // 入口文件
  entry: ‘./src/index.js‘,
  // 打包后输出的配置块
  output: {
    // 文件名
    filename: ‘bundle.js‘,
    // 调用resolve()设置路径
    path: path.resolve(__dirname, ‘dist‘)
  }
};

配置完成以后,只需要执行webpack即可开始打包。

Webpack 打包css文件

(1) 下载对应的loader加载器:

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

url-loader是对 file-loader高层封装,需要配合file-loader使用。

(2) 配置使用:

const path = require(‘path‘);

  module.exports = {
    entry: ‘./src/index.js‘,
    output: {
      filename: ‘bundle.js‘,
      path: path.resolve(__dirname, ‘dist‘)
    },
   // 添加模块配置
   module: {
     // 查找规则
     rules: [
       {
         test: /.css$/,
         // 要加载使用Loader
         use: [
           ‘style-loader‘,
           ‘css-loader‘
         ]
       }
     ]
   }
  };

Webpack打包图像文件

(1) 下载对应的loader加载器:

npm install --save-dev file-loader

(2) 配置使用:

const path = require(‘path‘);

  module.exports = {
    entry: ‘./src/index.js‘,
    output: {
      filename: ‘bundle.js‘,
      path: path.resolve(__dirname, ‘dist‘)
    },
    module: {
      rules: [
        {
          test: /.css$/,
          use: [
            ‘style-loader‘,
            ‘css-loader‘
          ]
        },
       // 添加模块配置项
       {
         test: /.(png|svg|jpg|gif)$/,
         use: [
           ‘file-loader‘
         ]
       }
      ]
    }
  };

Webpack热加载技术

(1) 下载对应的安装包:

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

(2) 配置使用:

  const path = require(‘path‘);
  const htmlWebpackPlugin = require(‘html-webpack-plugin‘);
  const CleanWebpackPlugin = require(‘clean-webpack-plugin‘);

  module.exports = {
    entry: {
      app: ‘./src/index.js‘,
      print: ‘./src/print.js‘
    },
   // 添加配置项   
   devtool: ‘inline-source-map‘,
   devServer: {
     // 服务器内容目录
     contentBase: ‘./dist‘
   },
    plugins: [
      new CleanWebpackPlugin([‘dist‘]),
      new HtmlWebpackPlugin({
        title: ‘Development‘
      })
    ],
    output: {
      filename: ‘[name].bundle.js‘,
      path: path.resolve(__dirname, ‘dist‘)
    }
  };

(3) 添加脚本命令:

{
    "name": "development",
    "version": "1.0.0",
    "description": "",
    "main": "webpack.config.js",
    "scripts": {
      "test": "echo "Error: no test specified" && exit 1",
      "watch": "webpack --watch",
      // 配置一个命令名称
+     "start": "webpack-dev-server --open",
      "build": "webpack"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "clean-webpack-plugin": "^0.1.16",
      "css-loader": "^0.28.4",
      "csv-loader": "^2.1.1",
      "file-loader": "^0.11.2",
      "html-webpack-plugin": "^2.29.0",
      "style-loader": "^0.18.2",
      "webpack": "^3.0.0",
      "xml-loader": "^1.2.1"
    }
  }

Webpack插件的使用

var webpack = require(‘webpack‘);
// 导入非 webpack 自带默认插件
var ExtractTextPlugin = require(‘extract-text-webpack-plugin‘);
var DashboardPlugin = require(‘webpack-dashboard/plugin‘);

// 在配置中添加插件
plugins: [
  // 构建优化插件
  new webpack.optimize.CommonsChunkPlugin({
    name: ‘vendor‘,
    filename: ‘vendor-[hash].min.js‘,
  }),
  new webpack.optimize.UglifyJsPlugin({
    compress: {
      warnings: false,
      drop_console: false,
    }
  }),
  new ExtractTextPlugin({
    filename: ‘build.min.css‘,
    allChunks: true,
  }),
  new webpack.IgnorePlugin(/^./locale$/, /moment$/),
  // 编译时(compile time)插件
  new webpack.DefinePlugin({
    ‘process.env.NODE_ENV‘: ‘"production"‘,
  }),
  // webpack-dev-server 强化插件
  new DashboardPlugin(),
  new webpack.HotModuleReplacementPlugin(),
]

以上是关于自动化构建工具WebPack的主要内容,如果未能解决你的问题,请参考以下文章

前端自动化构建工具之webpack

Webpack 简介

自动化构建工具WebPack

gulp webpack 区别

前端项目自动化构建工具——Webpack入门教程

gulp+webpack配置