接触webpack是好久之前的事情了,最近看了下webpack没想到都到4了。

webpack 是一个现代 JavaScript 应用程序的静态模块打包器(module bundler).

会创建1个依赖关系图(dependency graph),包含所有依赖的模块,然后将模块打包成1个或多个bundle.

webpack4 仍然支持高度可配,但完全可以不用配置文件了(基于mode)。

安装

淘宝源:npm config set registry https://registry.npm.taobao.org

升级npm:npm i npm -g

安装webpack:npm i -D webpack webpack-cli webpack-dev-server

运行webpack:npx webpack(Node 8.2+ 版本提供的npx命令)

基本特性

核心配置:

  • 入口(entry):
  • 输出(output):
  • loader:
  • 插件(plugins):

Entry

入口起点(entry point)指示 webpack 应该使用哪个模块,来作为构建其内部依赖图的开始。

可以通过在 webpack 配置中配置 entry 属性,来指定一个入口起点(或多个入口起点)。默认值为 ./src/index.js

webpack.config.js

  1. module.exports = {
  2. entry: {
  3. main: './src/index.js'
  4. },
  5. };

Output

output 属性告诉 webpack 在哪里输出它所创建的 bundles,以及如何命名这些文件,默认值为./dist/[name].js

webpack.config.js

  1. const path = require('path');
  2. module.exports = {
  3. entry: './src/index.js',
  4. output: {
  5. path: path.resolve(__dirname, 'dist'),
  6. filename: '[name].js'
  7. }
  8. };

Loader

loader 让 webpack 能够去处理那些非 JavaScript 文件(webpack 自身只理解 JavaScript)。

loaders 有2个核心参数:

  1. test 属性,用于标识出需要转换的某个或某些文件。
  2. use 属性,表示进行转换时,应该使用哪个 loader。
  1. const path = require('path');
  2. const config = {
  3. output: {
  4. filename: 'bundle.js'
  5. },
  6. module: {
  7. rules: [
  8. { test: /\.txt$/, use: 'raw-loader' }
  9. ]
  10. }
  11. };
  12. module.exports = config;

Plugins

插件的范围包括,从打包优化和压缩,一直到重新定义环境中的变量。插件接口功能极其强大,可以用来处理各种各样的任务。

webpack.config.js

  1. const HtmlWebpackPlugin = require('html-webpack-plugin'); // 通过 npm 安装
  2. const webpack = require('webpack'); // 用于访问内置插件
  3. const config = {
  4. module: {
  5. rules: [
  6. { test: /\.txt$/, use: 'raw-loader' }
  7. ]
  8. },
  9. plugins: [
  10. new webpack.optimize.UglifyJsPlugin(),
  11. new HtmlWebpackPlugin({template: './src/index.html'})
  12. ]
  13. };
  14. module.exports = config;

Mode

通过选择 development 或 production 之中的一个,来设置 mode 参数

webpack.config.js

  1. module.exports = {
  2. mode: 'production'
  3. };

mode.js

  1. // webpack.development.config.js
  2. module.exports = {
  3. + mode: 'development'
  4. - plugins: [
  5. - new webpack.NamedModulesPlugin(),
  6. - new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("development") }),
  7. - ]
  8. }
  1. // webpack.production.config.js
  2. module.exports = {
  3. + mode: 'production',
  4. - plugins: [
  5. - new UglifyJsPlugin(/* ... */),
  6. - new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production") }),
  7. - new webpack.optimize.ModuleConcatenationPlugin(),
  8. - new webpack.NoEmitOnErrorsPlugin()
  9. - ]
  10. }

常用插件

HtmlWebpackPlugin:

Options

  1. const HtmlWebpackPlugin = require('html-webpack-plugin');
  2. new HtmlWebpackPlugin({ template: 'src/index.html', minify: true, hash: true })

CleanWebpackPlugin:

  1. const CleanWebpackPlugin = require('clean-webpack-plugin');
  2. new CleanWebpackPlugin(['dist'])

MiniCssExtractPlugin(ExtractTextPlugin):

  1. new MiniCssExtractPlugin({ filename: "[name].css",chunkFilename: "[id].css" })
  2. module: {
  3. rules: [{
  4. test: /\.css$/,
  5. use: [
  6. MiniCssExtractPlugin.loader,
  7. 'css-loader'
  8. ]}
  9. ]
  10. }

SplitChunksPlugin:

  1. module.exports = {
  2. mode: 'development',
  3. entry: {
  4. main: './src/index.js',
  5. vendors: 'lodash'
  6. },
  7. optimization: {
  8. splitChunks: {
  9. cacheGroups: {
  10. vendors: {
  11. test: /[\\/]node_modules[\\/]/,
  12. name: "vendors",
  13. chunks: "initial"
  14. }
  15. }
  16. }
  17. }
  18. }

配置示例

package

package.json

  1. {
  2. "scripts": {
  3. "test": "echo \"Error: no test specified\" && exit 1",
  4. "start": "webpack-dev-server --open",
  5. "build": "webpack --config webpack.prod.js"
  6. },
  7. "devDependencies": {
  8. "babel-loader": "^7.1.4",
  9. "babel-preset-react": "^6.24.1",
  10. "babel-plugin-import": "^1.7.0",
  11. "clean-webpack-plugin": "^0.1.19",
  12. "css-loader": "^0.28.11",
  13. "html-webpack-plugin": "^3.2.0",
  14. "mini-css-extract-plugin": "^0.4.0",
  15. "webpack": "^4.8.3",
  16. "webpack-cli": "^2.1.3",
  17. "webpack-dev-server": "^3.1.4"
  18. },
  19. "dependencies": {
  20. "antd": "^3.5.2",
  21. "babel-plugin-syntax-dynamic-import": "^6.18.0",
  22. "express": "^4.16.3",
  23. "lodash": "^4.17.10",
  24. "react": "^16.3.2",
  25. "react-dom": "^16.3.2",
  26. "react-loadable": "^5.4.0",
  27. "react-redux": "^5.0.7",
  28. "react-router": "^4.2.0",
  29. "react-router-dom": "^4.2.2",
  30. "redux": "^4.0.0",
  31. "redux-logger": "^3.0.6",
  32. "redux-promise": "^0.6.0",
  33. "redux-saga": "^0.16.0",
  34. "redux-thunk": "^2.2.0"
  35. }
  36. }

开发环境

  1. const CleanWebpackPlugin = require('clean-webpack-plugin');
  2. const HtmlWebpackPlugin = require('html-webpack-plugin');
  3. const MiniCssExtractPlugin = require("mini-css-extract-plugin");
  4. const path = require('path');
  5. module.exports = {
  6. mode: 'development',
  7. entry: {
  8. main: './src/index.js',
  9. },
  10. devtool: 'inline-source-map',
  11. devServer: {
  12. contentBase: './dist'
  13. },
  14. output: {
  15. path: path.resolve(__dirname, 'dist'),
  16. filename: '[name].js',
  17. },
  18. module: {
  19. rules: [{
  20. test: /\.css$/,
  21. use: [
  22. MiniCssExtractPlugin.loader,
  23. 'css-loader'
  24. ]
  25. }, {
  26. test: /\.(js|jsx)$/,
  27. loader: 'babel-loader',
  28. options: {
  29. presets: ['react'],
  30. plugins: [
  31. ["import", { "libraryName": "antd", "style": "css" }]
  32. ]
  33. },
  34. exclude: /node_modules/
  35. }]
  36. },
  37. plugins: [
  38. new CleanWebpackPlugin(['dist']),
  39. new HtmlWebpackPlugin({ minify: true, hash: true }),
  40. new MiniCssExtractPlugin({ filename: "[name].css", chunkFilename: "[id].css" })
  41. ],
  42. optimization: {
  43. splitChunks: {
  44. cacheGroups: {
  45. common: {
  46. test: /[\\/]node_modules[\\/]/,
  47. name: "common",
  48. chunks: "initial",
  49. enforce: true
  50. },
  51. }
  52. }
  53. }
  54. };

生产环境

  1. const CleanWebpackPlugin = require('clean-webpack-plugin');
  2. const HtmlWebpackPlugin = require('html-webpack-plugin');
  3. const MiniCssExtractPlugin = require("mini-css-extract-plugin");
  4. const path = require('path');
  5. module.exports = {
  6. mode: 'production',
  7. entry: {
  8. main: './src/index.js',
  9. },
  10. devtool: 'source-map',
  11. devServer: {
  12. contentBase: './dist',
  13. host: '192.168.0.75'
  14. },
  15. output: {
  16. path: path.resolve(__dirname, 'dist'),
  17. filename: '[name].js',
  18. },
  19. module: {
  20. rules: [{
  21. test: /\.css$/,
  22. use: [
  23. MiniCssExtractPlugin.loader,
  24. 'css-loader'
  25. ]
  26. }, {
  27. test: /\.(js|jsx)$/,
  28. loader: 'babel-loader',
  29. options: {
  30. presets: ['react'],
  31. plugins: []
  32. },
  33. exclude: /node_modules/
  34. }]
  35. },
  36. plugins: [
  37. new CleanWebpackPlugin(['dist']),
  38. new HtmlWebpackPlugin({ template: 'src/index.html', minify: true, hash: true }),
  39. new MiniCssExtractPlugin({ filename: "[name].css", chunkFilename: "[id].css" })
  40. ],
  41. externals: {
  42. lodash: '_',
  43. react: 'React',
  44. 'react-dom': 'ReactDOM',
  45. antd: 'antd'
  46. },
  47. optimization: {
  48. splitChunks: {
  49. cacheGroups: {
  50. common: {
  51. test: /[\\/]node_modules[\\/]/,
  52. name: "common",
  53. chunks: "initial",
  54. enforce: true
  55. },
  56. }
  57. }
  58. }
  59. };

React从入门到放弃之前奏(1):webpack4简介的更多相关文章

  1. React从入门到放弃之前奏(5):ReactRouter4

    概念 安装:npm i -S react-router react-router-dom GitHub:ReactTraining/react-router React Router中有三种类型的组件 ...

  2. React从入门到放弃之前奏(2):React简介

    本系列将尽可能使用ES6(ES2015)语法.所以均在上节webpack的基础上做开发. React是Facebook开发的一款JS库,因为基于Virtual DOM,所以响应速度快,以及支持跨平台. ...

  3. React从入门到放弃之前奏(3):Redux简介

    安装 npm i -S redux react-redux redux-devtools 概念 在redux中分为3个对象:Action.Reducer.Store Action 对行为(如用户行为) ...

  4. React从入门到放弃之前奏(4):Redux中间件

    redux 提供了类似后端 Express 的中间件概念. 最适合扩展的是redux中的 store.dispatch 方法,中间件实际就是通过 override redux的store.dispat ...

  5. 在 2016 年学 JavaScript 是一种什么样的体验?(React从入门到放弃)

    jquery 年代 vs 前端模块化 http://blog.csdn.net/offbye/article/details/52793921 ++ 嘿,我最近接到一个 Web 项目,不过老实说,我这 ...

  6. ubuntu-docker入门到放弃(七)Dockerfile简介

    一.dockerfile基本结构 最简单的理解就是dockerfile实际上是一些命令的堆叠,有点像最基础的shell脚本,没有if 没有for,就是串行的一堆命令. 一般而言,dockerfile分 ...

  7. D3.js从入门到“放弃”指南

    前言 近期略有点诸事不顺,趁略有闲余之时,玩起D3.js.之前实际项目中主要是用各种chart如hightchart.echarts等,这些图形库玩起来貌都是完美的,一切皆可配置,但几年前接触了D3之 ...

  8. 一天带你入门到放弃vue.js(一)

    写在前面的话! 每个新的框架入手都会进行一些列的扯犊子!这里不多说那么多!简简单单说一下vue吧! Vue.js是目前三大框架(angular,vue,react)之一,是渐进式js框架,据说是摒弃了 ...

  9. 小白学 Python 爬虫(28):自动化测试框架 Selenium 从入门到放弃(下)

    人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...

随机推荐

  1. 怎样写一个与Win8 IE11兼容的标准BHO?

    怎样写一个与Win8 IE11兼容的标准BHO? 环境:Windows8.1 x86 IE11(其它环境未讨论) 作者:magictong 日期:2014/02/02 概述 微软在2013年6月份推出 ...

  2. 不要使用jQuery触发原生事件

    原文链接: DO NOT TRIGGER REAL EVENT NAMES WITH JQUERY! 原文日期: 2014年02月26日 翻译日期: 2014年03月2日 翻译人员: 铁锚 JavaS ...

  3. Advanced Pricing - How to source Pricing Attributes using QP_CUSTOM_SOURCE.Get_Custom_Attribute_Valu

    详细内容需要参考文档:Oracle 11i Advanced Pricing-Don't Customize, Extend! utl:http://blog.csdn.net/cai_xingyun ...

  4. C语言字符串的常见特殊操作(除了string.c实现的那些接口)

    字符串操作中,必须掌握的一些之前已经在文章有写过了,比如说字符串查找,字符串粘帖,字符串拷贝等等,这些在标准C库的string.c中已经有实现,故包含#include <string.h> ...

  5. C++继承中的public/protected/private

    今天杨老师讲到C++的继承的时候用一个表来说明子类继承父类后访问权限的变化,如下表: 注:在本类中,protected与private是相同的,但protected可以被继承,而private却不行. ...

  6. TCP连接建立系列 — TCP选项解析

    本文主要分析:在收到客户端的SYN包时,服务器端是如何解析它所携带的TCP选项,并结合本端情况决定是否予以支持. 内核版本:3.6 Author:zhangskd @ csdn blog 概述 收到客 ...

  7. sqlserver2008中删除了windows用户,导致无法登陆的解决方案

    打开管理工具中的"服务",找到并关闭SQL Server服务.进入命令进入SQL Server 2008的安装目录,找到sqlservr.exe文件,执行命令:sqlservr - ...

  8. Prefix tree

    Prefix tree The trie, or prefix tree, is a data structure for storing strings or other sequences in ...

  9. c++ list 合并操作函数实例

    #include <list> #include <iostream> using namespace std; //list 链表的打印 void print(list< ...

  10. javascript加RoR实现JSONP

    我们知道不同域中的js代码受同源策略的限制,不同域中的AJAX同样受此限制,不过使用html中的script远程脚本可以跳过该限制,下面我们实际看一下利用RoR和js如何实现所谓的JSONP. 这里只 ...