webpack打包各种javascript文件

(本文只是提供一个学习记录,大部分内容来自网络)


一,打包js文件和es6代码   

1,webpack命令打包js文件     

Tip: 在webpack4.x之前可以直接在命令行工具中使用webpack命令(全局安装了webpack),webpack4.x之后需要安装webpack-cli      

  1. webpack --entry .\src\app.js --output ./src/b.js --mode development

  webpack --entry <入口文件> --output <输出文件> --mode 模式 

更多具体参数可以:webpack --help

  1. Config options:
  2. --config Path to the config file
  3. [string] [default: webpack.config.js or webpackfile.js]
  4. --config-register, -r Preload one or more modules before loading the webpack
  5. configuration [array] [default: module id or path]
  6. --config-name Name of the config to use [string]
  7. --env Environment passed to the config, when it is a function
  8. --mode Enable production optimizations or development hints.
  9. [choices: "development", "production", "none"]
  10.  
  11. Basic options:
  12. --context The base directory (absolute path!) for resolving the `entry`
  13. option. If `output.pathinfo` is set, the included pathinfo is
  14. shortened to this directory.
  15. [string] [default: The current directory]
  16. --entry The entry point(s) of the compilation. [string]
  17. --watch, -w Enter watch mode, which rebuilds on file change. [boolean]
  18. --debug Switch loaders to debug mode [boolean]
  19. --devtool A developer tool to enhance debugging. [string]
  20. -d shortcut for --debug --devtool eval-cheap-module-source-map
  21. --output-pathinfo [boolean]
  22. -p shortcut for --optimize-minimize --define
  23. process.env.NODE_ENV="production" [boolean]
  24. --progress Print compilation progress in percentage [boolean]
  25.  
  26. Module options:
  27. --module-bind Bind an extension to a loader [string]
  28. --module-bind-post Bind an extension to a post loader [string]
  29. --module-bind-pre Bind an extension to a pre loader [string]
  30.  
  31. Output options:
  32. --output, -o The output path and file for compilation assets
  33. --output-path The output directory as **absolute path**
  34. (required).
  35. [string] [default: The current directory]
  36. --output-filename Specifies the name of each output file on disk.
  37. You must **not** specify an absolute path here!
  38. The `output.path` option determines the location
  39. on disk the files are written to, filename is
  40. used solely for naming the individual files.
  41. [string] [default: [name].js]
  42. --output-chunk-filename The filename of non-entry chunks as relative
  43. path inside the `output.path` directory.
  44. [string] [default: filename with [id] instead of [name] or [id] prefixed]
  45. --output-source-map-filename The filename of the SourceMaps for the
  46. JavaScript files. They are inside the
  47. `output.path` directory. [string]
  48. --output-public-path The `publicPath` specifies the public URL
  49. address of the output files when referenced in a
  50. browser. [string]
  51. --output-jsonp-function The JSONP function used by webpack for async
  52. loading of chunks. [string]
  53. --output-pathinfo Include comments with information about the
  54. modules. [boolean]
  55. --output-library Expose the exports of the entry point as library
  56. [array]
  57. --output-library-target Type of library
  58. [string] [choices: "var", "assign", "this", "window", "self", "global",
  59. "commonjs", "commonjs2", "commonjs-module", "amd", "umd", "umd2", "jsonp"]
  60.  
  61. Advanced options:
  62. --records-input-path Store compiler state to a json file. [string]
  63. --records-output-path Load compiler state from a json file. [string]
  64. --records-path Store/Load compiler state from/to a json file. This
  65. will result in persistent ids of modules and
  66. chunks. An absolute path is expected. `recordsPath`
  67. is used for `recordsInputPath` and
  68. `recordsOutputPath` if they left undefined.[string]
  69. --define Define any free var in the bundle [string]
  70. --target Environment to build for [string]
  71. --cache Cache generated modules and chunks to improve
  72. performance for multiple incremental builds.
  73. [boolean] [default: It's enabled by default when watching]
  74. --watch-stdin, --stdin Stop watching when stdin stream has ended [boolean]
  75. --watch-aggregate-timeout Delay the rebuilt after the first change. Value is
  76. a time in ms. [number]
  77. --watch-poll Enable polling mode for watching [string]
  78. --hot Enables Hot Module Replacement [boolean]
  79. --prefetch Prefetch this request (Example: --prefetch
  80. ./file.js) [string]
  81. --provide Provide these modules as free vars in all modules
  82. (Example: --provide jQuery=jquery) [string]
  83. --labeled-modules Enables labeled modules [boolean]
  84. --plugin Load this plugin [string]
  85. --bail Report the first error as a hard error instead of
  86. tolerating it. [boolean] [default: null]
  87. --profile Capture timing information for each module.
  88. [boolean] [default: null]
  89.  
  90. Resolving options:
  91. --resolve-alias Redirect module requests [string]
  92. --resolve-extensions Redirect module requests [array]
  93. --resolve-loader-alias Setup a loader alias for resolving [string]
  94.  
  95. Optimizing options:
  96. --optimize-max-chunks Try to keep the chunk count below a limit
  97. --optimize-min-chunk-size Minimal size for the created chunk
  98. --optimize-minimize Enable minimizing the output. Uses
  99. optimization.minimizer. [boolean]
  100.  
  101. Stats options:
  102. --color, --colors Force colors on the console
  103. [boolean] [default: (supports-color)]
  104. --no-color, --no-colors Force no colors on the console [boolean]
  105. --sort-modules-by Sorts the modules list by property in module
  106. [string]
  107. --sort-chunks-by Sorts the chunks list by property in chunk
  108. [string]
  109. --sort-assets-by Sorts the assets list by property in asset
  110. [string]
  111. --hide-modules Hides info about modules [boolean]
  112. --display-exclude Exclude modules in the output [string]
  113. --display-modules Display even excluded modules in the output
  114. [boolean]
  115. --display-max-modules Sets the maximum number of visible modules in
  116. output [number]
  117. --display-chunks Display chunks in the output [boolean]
  118. --display-entrypoints Display entry points in the output [boolean]
  119. --display-origins Display origins of chunks in the output
  120. [boolean]
  121. --display-cached Display also cached modules in the output
  122. [boolean]
  123. --display-cached-assets Display also cached assets in the output
  124. [boolean]
  125. --display-reasons Display reasons about module inclusion in the
  126. output [boolean]
  127. --display-depth Display distance from entry point for each
  128. module [boolean]
  129. --display-used-exports Display information about used exports in
  130. modules (Tree Shaking) [boolean]
  131. --display-provided-exports Display information about exports provided
  132. from modules [boolean]
  133. --display-optimization-bailout Display information about why optimization
  134. bailed out for modules [boolean]
  135. --display-error-details Display details about errors [boolean]
  136. --display Select display preset
  137. [string] [choices: "", "verbose", "detailed", "normal", "minimal",
  138. "errors-only", "none"]
  139. --verbose Show more details [boolean]
  140. --info-verbosity Controls the output of lifecycle messaging
  141. e.g. Started watching files...
  142. [string] [choices: "none", "info", "verbose"] [default: "info"]
  143. --build-delimiter Display custom text after build output[string]

2,使用配置文件打包

  1. const path = require('path');
  2.  
  3. module.exports = {
  4. mode: "production", // "production" | "development" | "none" // Chosen mode tells webpack to use its built-in optimizations accordingly.
  5.  
  6. entry: "./app/entry", // string | object | array // 这里应用程序开始执行
     //entry: ["./app/entry1", "./app/entry2"]
    //entry: {
     //   a: "./app/entry-a",
     //   b: ["./app/entry-b", "./app/entry-b"]
     // } 
  7. // webpack 开始打包
  8.  
  9. output: {
  10. // webpack 如何输出结果的相关选项
  11.  
  12. path: path.resolve(__dirname, "dist"), // string
  13. // 所有输出文件的目标路径
  14. // 必须是绝对路径(使用 Node.js 的 path 模块)
  15.  
  16. filename: "bundle.js", // string // 「入口分块(entry chunk)」的文件名模板(出口分块?)
  17.  
  18. publicPath: "/assets/", // string // 输出解析文件的目录,url 相对于 HTML 页面
  19.  
  20. library: "MyLibrary", // string,
  21. // 导出库(exported library)的名称
  22.  
  23. libraryTarget: "umd", // 通用模块定义 // 导出库(exported library)的类型
  24.  
  25. /* 高级输出配置(点击显示) */ },
  26.  
  27. module: {
  28. // 关于模块配置
  29.  
  30. rules: [
  31. // 模块规则(配置 loader、解析器等选项)
  32.  
  33. {
  34. test: /\.jsx?$/,
  35. include: [
  36. path.resolve(__dirname, "app")
  37. ],
  38. exclude: [
  39. path.resolve(__dirname, "app/demo-files")
  40. ],
  41. // 这里是匹配条件,每个选项都接收一个正则表达式或字符串
  42. // test 和 include 具有相同的作用,都是必须匹配选项
  43. // exclude 是必不匹配选项(优先于 test 和 include)
  44. // 最佳实践:
  45. // - 只在 test 和 文件名匹配 中使用正则表达式
  46. // - 在 include 和 exclude 中使用绝对路径数组
  47. // - 尽量避免 exclude,更倾向于使用 include
  48.  
  49. issuer: { test, include, exclude },
  50. // issuer 条件(导入源)
  51.  
  52. enforce: "pre",
  53. enforce: "post",
  54. // 标识应用这些规则,即使规则覆盖(高级选项)
  55.  
  56. loader: "babel-loader",
  57. // 应该应用的 loader,它相对上下文解析
  58. // 为了更清晰,`-loader` 后缀在 webpack 2 中不再是可选的
  59. // 查看 webpack 1 升级指南。
  60.  
  61. options: {
  62. presets: ["es2015"]
  63. },
  64. // loader 的可选项
  65. },
  66.  
  67. {
  68. test: /\.html$/,
  69. test: "\.html$"
  70.  
  71. use: [
  72. // 应用多个 loader 和选项
  73. "htmllint-loader",
  74. {
  75. loader: "html-loader",
  76. options: {
  77. /* ... */
  78. }
  79. }
  80. ]
  81. },
  82.  
  83. { oneOf: [ /* rules */ ] },
  84. // 只使用这些嵌套规则之一
  85.  
  86. { rules: [ /* rules */ ] },
  87. // 使用所有这些嵌套规则(合并可用条件)
  88.  
  89. { resource: { and: [ /* 条件 */ ] } },
  90. // 仅当所有条件都匹配时才匹配
  91.  
  92. { resource: { or: [ /* 条件 */ ] } },
  93. { resource: [ /* 条件 */ ] },
  94. // 任意条件匹配时匹配(默认为数组)
  95.  
  96. { resource: { not: /* 条件 */ } }
  97. // 条件不匹配时匹配
  98. ],
  99.  
  100. /* 高级模块配置(点击展示) */ },
  101.  
  102. resolve: {
  103. // 解析模块请求的选项
  104. // (不适用于对 loader 解析)
  105.  
  106. modules: [
  107. "node_modules",
  108. path.resolve(__dirname, "app")
  109. ],
  110. // 用于查找模块的目录
  111.  
  112. extensions: [".js", ".json", ".jsx", ".css"],
  113. // 使用的扩展名
  114.  
  115. alias: {
  116. // 模块别名列表
  117.  
  118. "module": "new-module",
  119. // 起别名:"module" -> "new-module" 和 "module/path/file" -> "new-module/path/file"
  120.  
  121. "only-module$": "new-module",
  122. // 起别名 "only-module" -> "new-module",但不匹配 "only-module/path/file" -> "new-module/path/file"
  123.  
  124. "module": path.resolve(__dirname, "app/third/module.js"),
  125. // 起别名 "module" -> "./app/third/module.js" 和 "module/file" 会导致错误
  126. // 模块别名相对于当前上下文导入
  127. },
  128. /* 可供选择的别名语法(点击展示) */
  129. /* 高级解析选项(点击展示) */ },
  130.  
  131. performance: {
  132. hints: "warning", // 枚举 maxAssetSize: 200000, // 整数类型(以字节为单位)
  133. maxEntrypointSize: 400000, // 整数类型(以字节为单位)
  134. assetFilter: function(assetFilename) {
  135. // 提供资源文件名的断言函数
  136. return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
  137. }
  138. },
  139.  
  140. devtool: "source-map", // enum // 通过在浏览器调试工具(browser devtools)中添加元信息(meta info)增强调试
  141. // 牺牲了构建速度的 `source-map' 是最详细的。
  142.  
  143. context: __dirname, // string(绝对路径!)
  144. // webpack 的主目录
  145. // entry 和 module.rules.loader 选项
  146. // 相对于此目录解析
  147.  
  148. target: "web", // 枚举 // 包(bundle)应该运行的环境
  149. // 更改 块加载行为(chunk loading behavior) 和 可用模块(available module)
  150.  
  151. externals: ["react", /^@angular\//], // 不要遵循/打包这些模块,而是在运行时从环境中请求他们
  152.  
  153. stats: "errors-only", // 精确控制要显示的 bundle 信息
  154.  
  155. devServer: {
  156. proxy: { // proxy URLs to backend development server
  157. '/api': 'http://localhost:3000'
  158. },
  159. contentBase: path.join(__dirname, 'public'), // boolean | string | array, static file location
  160. compress: true, // enable gzip compression
  161. historyApiFallback: true, // true for index.html upon 404, object for multiple paths
  162. hot: true, // hot module replacement. Depends on HotModuleReplacementPlugin
  163. https: false, // true for self-signed, object for cert authority
  164. noInfo: true, // only errors & warns on hot reload
  165. // ...
  166. },
  167.  
  168. plugins: [
  169. // ...
  170. ],
  171. // 附加插件列表
  172.  
  173. /* 高级配置(点击展示) */}

说明:

  1,运行配置文件,可在package.json下的`scripts`里添加: { "build": "webpack --config webpack.config.js"},其中配置文件的默认名字为webpack.config.js,如果是其他名字可以用config指认。

  2,entry对象是webpack的打包的入口文件。webpack会根据entry的配置进行查找入口文件和所有依赖文件并且构建bundle

  3,output对象指示webpack将如何去输出,以及在哪里输出你的[bundle,asset和其他你所打包或者使用wenbpack载入的任何内容]

3,webpack配合babel打包ES6、7

  由于ES6的普及和得心用手,几乎所有项目中都会使用es6语法。但是浏览器对其支持并不友好,所以需要把es6降级到大部分浏览器都能解析的es5。babel就是这样一个作用的工具。

  babel-loader: 只是起到一个通知的角色,通知babel你需要干活了,在webpack中是这样的:

  

  1.   module: {
  2. rules: [
  3. {
  4. test: /\.js$/,
  5. exclude: /node_modules/,
  6. use: {
  7. loader: 'babel-loader',
  8. options: { // 这个配置项我们一般单独拿出来,创建一个‘.babelrc’文件来单独存放配置项
  9.          presets: ['@babel/preset-env'],// babel预设
  10.         plugin: ['@babel/plugin-proposal-object-rest-spread'] // 所需要使用的插件
  11.         }
  12. }
  13. }
  14.   }

babel-core

如果说 babel-loader 是告诉webpack我要对js文件进行代码兼容性编译,那么,webpack接下来就是要找babel,而bable的入口就是 babel-core ,只有通过它,webpack才能使用各种babel的api(前提是你安装了相关的api)。

babel-preset-env

  首先,介绍下历史背景,对了解和学习 babel-preset-env 有帮助。

最初,为了让开发者能够尽早用上新的JS特性,babel团队开发了babel-preset-latest。这个preset比较特殊,它是多个preset的集合(es2015+),并且随着ECMA规范的更新更增加它的内容。

比如,当前(2018.06.02),它包含的preset包括:es2017、es1016、es2015。

到了明年,可能它包含的preset就包括:es2018、es2017、es2016、es2015。

随着时间的推移,babel-preset-latest 包含的插件越来越多,这带来了如下问题:

  1. 加载的插件越来越多,编译速度会越来越慢;
  2. 随着用户浏览器的升级,ECMA规范的支持逐步完善,编译至低版本规范的必要性在减少(比如ES6 -> ES5),多余的转换不单降低执行效率,还浪费带宽。

因为上述问题的存在,babel官方推出了babel-preset-env插件。它可以根据开发者的配置,按需加载插件。配置项大致包括:

  1. 需要支持的平台:比如node、浏览器等。
  2. 需要支持的平台的版本:比如支持node@6.1等。

默认配置的情况下,它跟 babel-preset-latest 是等同的,会加载从es2015开始的所有preset。

配置文件.babelrc如下,当前为默认配置

  1. {
  2. "presets": [ "env" ]
  3. }

同时可以针对node和浏览器版本去进行不同的配置,比如,我们需要支持IE8+,chrome2+,那么可以这样配置:

  1. {
  2. "presets": [
  3. ["env", {
  4. "targets": {
  5. "browsers": [ "ie >= 8", "chrome >= 62" ]
  6. }
  7. }]
  8. ]
  9. }

  预设只能将ES6语法编译为你指定的ES版本语法,例如:箭头函数,但是像 Array.from 这样的API呢他无能为力。那么,怎么办呢?

babel-polypill、babel-runtime

  babel-polypill就是提供了es6新方法的解决方案,不过使用的时候是在入口文件全局引入,这样会污染全局变量,所以需要babel-runtime,这样就不要全局引入而导致全局变量的污染

  

  1. {
  2. "presets": [
  3. ["env", {
  4. "targets": {
  5. "browsers": [ "ie >= 8", "chrome >= 62" ]
  6. }
  7. }]
  8. ],
  9. "plugins": ["transform-runtime"] //
  10. }

webpack4学习笔记(二)的更多相关文章

  1. Webpack4 学习笔记二 CSS模块转换

    前言 此内容是个人学习笔记,以便日后翻阅.非教程,如有错误还请指出 webpack 打包css模块 webpack是js模块打包器, 如果在入口文件引入css文件或其它的less.sass等文件,需要 ...

  2. WPF的Binding学习笔记(二)

    原文: http://www.cnblogs.com/pasoraku/archive/2012/10/25/2738428.htmlWPF的Binding学习笔记(二) 上次学了点点Binding的 ...

  3. AJax 学习笔记二(onreadystatechange的作用)

    AJax 学习笔记二(onreadystatechange的作用) 当发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态XMLHttpRequest对象提供了on ...

  4. [Firefly引擎][学习笔记二][已完结]卡牌游戏开发模型的设计

    源地址:http://bbs.9miao.com/thread-44603-1-1.html 在此补充一下Socket的验证机制:socket登陆验证.会采用session会话超时的机制做心跳接口验证 ...

  5. JMX学习笔记(二)-Notification

    Notification通知,也可理解为消息,有通知,必然有发送通知的广播,JMX这里采用了一种订阅的方式,类似于观察者模式,注册一个观察者到广播里,当有通知时,广播通过调用观察者,逐一通知. 这里写 ...

  6. java之jvm学习笔记二(类装载器的体系结构)

    java的class只在需要的时候才内转载入内存,并由java虚拟机的执行引擎来执行,而执行引擎从总的来说主要的执行方式分为四种, 第一种,一次性解释代码,也就是当字节码转载到内存后,每次需要都会重新 ...

  7. Java IO学习笔记二

    Java IO学习笔记二 流的概念 在程序中所有的数据都是以流的方式进行传输或保存的,程序需要数据的时候要使用输入流读取数据,而当程序需要将一些数据保存起来的时候,就要使用输出流完成. 程序中的输入输 ...

  8. 《SQL必知必会》学习笔记二)

    <SQL必知必会>学习笔记(二) 咱们接着上一篇的内容继续.这一篇主要回顾子查询,联合查询,复制表这三类内容. 上一部分基本上都是简单的Select查询,即从单个数据库表中检索数据的单条语 ...

  9. NumPy学习笔记 二

    NumPy学习笔记 二 <NumPy学习笔记>系列将记录学习NumPy过程中的动手笔记,前期的参考书是<Python数据分析基础教程 NumPy学习指南>第二版.<数学分 ...

  10. Learning ROS for Robotics Programming Second Edition学习笔记(二) indigo tools

    中文译著已经出版,详情请参考:http://blog.csdn.net/ZhangRelay/article/category/6506865 Learning ROS for Robotics Pr ...

随机推荐

  1. iOS图片压缩上传

    本文实例为大家分享了iOS实现压缩图片上传功能,供大家参考,具体内容如下 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 2 ...

  2. 思科ACL不连续通配符掩码的计算

    access-list 120 permit ip 10.0.0.0 0.0.0.191 any     这条ACL看似简单,却又复杂,因为正常我们见到的通配符掩码都是诸如0.0.0.255(255. ...

  3. HTML5中的拖放

    关于HTML5中的拖放 拖放(Drag 和 Drop)是一种常见的特性,即抓取对象以后拖到另一个位置,在 HTML5 中,拖放是标准的组成部分.在HTML5中用户可以使用鼠标选择一个可拖动元素,将元素 ...

  4. 原生sqlServer数据库连接

    package tj.test.demo; import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Sta ...

  5. js学习笔记23----窗口尺寸及窗口事件

    窗口尺寸: 可视区的尺寸 document.documentElement.clientWidth document.documentElement.clientHeight 滚动距离 documen ...

  6. EasyUI Window和Layout

    我们建立tabs内容. <div class="easyui-window" title="Layout Window" icon="icon- ...

  7. Python之查询美国护照状态

    该程序会每隔至少1秒进行一次护照状态查询 需要修改passportNo变量为自己的护照号码. 另外需要pip install beautifulsoup4 #coding=utf-8 import r ...

  8. 代码生成利器:IDEA 强大的 Live Templates

    Java 开发过程经常需要编写有固定格式的代码,例如说声明一个私有变量, logger 或者 bean 等等.对于这种小范围的代码生成,我们可以利用 IDEA 提供的 Live Templates 功 ...

  9. Spring Framework 官方文档学习(一)介绍

    http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#overview-maven-bom ...

  10. Generator生成器函数

    接触过Ajax请求的会遇到过异步调用的问题,为了保证调用顺序的正确性,一般我们会在回调函数中调用,也有用到一些新的解决方案如Promise相关的技术. 在异步编程中,还有一种常用的解决方案,它就是Ge ...