(本文只是提供一個學習記錄,大部份內容來自網絡)javascript
一,打包js文件和es6代碼 css
1,webpack命令打包js文件 html
Tip: 在webpack4.x以前能夠直接在命令行工具中使用webpack命令(全局安裝了webpack),webpack4.x以後須要安裝webpack-cli java
1 webpack --entry .\src\app.js --output ./src/b.js --mode development
webpack --entry <入口文件> --output <輸出文件> --mode 模式 node
更多具體參數能夠:webpack --helpreact
Config options: --config Path to the config file [string] [default: webpack.config.js or webpackfile.js] --config-register, -r Preload one or more modules before loading the webpack configuration [array] [default: module id or path] --config-name Name of the config to use [string] --env Environment passed to the config, when it is a function --mode Enable production optimizations or development hints. [choices: "development", "production", "none"] Basic options: --context The base directory (absolute path!) for resolving the `entry` option. If `output.pathinfo` is set, the included pathinfo is shortened to this directory. [string] [default: The current directory] --entry The entry point(s) of the compilation. [string] --watch, -w Enter watch mode, which rebuilds on file change. [boolean] --debug Switch loaders to debug mode [boolean] --devtool A developer tool to enhance debugging. [string] -d shortcut for --debug --devtool eval-cheap-module-source-map --output-pathinfo [boolean] -p shortcut for --optimize-minimize --define process.env.NODE_ENV="production" [boolean] --progress Print compilation progress in percentage [boolean] Module options: --module-bind Bind an extension to a loader [string] --module-bind-post Bind an extension to a post loader [string] --module-bind-pre Bind an extension to a pre loader [string] Output options: --output, -o The output path and file for compilation assets --output-path The output directory as **absolute path** (required). [string] [default: The current directory] --output-filename Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files. [string] [default: [name].js] --output-chunk-filename The filename of non-entry chunks as relative path inside the `output.path` directory. [string] [default: filename with [id] instead of [name] or [id] prefixed] --output-source-map-filename The filename of the SourceMaps for the JavaScript files. They are inside the `output.path` directory. [string] --output-public-path The `publicPath` specifies the public URL address of the output files when referenced in a browser. [string] --output-jsonp-function The JSONP function used by webpack for async loading of chunks. [string] --output-pathinfo Include comments with information about the modules. [boolean] --output-library Expose the exports of the entry point as library [array] --output-library-target Type of library [string] [choices: "var", "assign", "this", "window", "self", "global", "commonjs", "commonjs2", "commonjs-module", "amd", "umd", "umd2", "jsonp"] Advanced options: --records-input-path Store compiler state to a json file. [string] --records-output-path Load compiler state from a json file. [string] --records-path Store/Load compiler state from/to a json file. This will result in persistent ids of modules and chunks. An absolute path is expected. `recordsPath` is used for `recordsInputPath` and `recordsOutputPath` if they left undefined.[string] --define Define any free var in the bundle [string] --target Environment to build for [string] --cache Cache generated modules and chunks to improve performance for multiple incremental builds. [boolean] [default: It's enabled by default when watching] --watch-stdin, --stdin Stop watching when stdin stream has ended [boolean] --watch-aggregate-timeout Delay the rebuilt after the first change. Value is a time in ms. [number] --watch-poll Enable polling mode for watching [string] --hot Enables Hot Module Replacement [boolean] --prefetch Prefetch this request (Example: --prefetch ./file.js) [string] --provide Provide these modules as free vars in all modules (Example: --provide jQuery=jquery) [string] --labeled-modules Enables labeled modules [boolean] --plugin Load this plugin [string] --bail Report the first error as a hard error instead of tolerating it. [boolean] [default: null] --profile Capture timing information for each module. [boolean] [default: null] Resolving options: --resolve-alias Redirect module requests [string] --resolve-extensions Redirect module requests [array] --resolve-loader-alias Setup a loader alias for resolving [string] Optimizing options: --optimize-max-chunks Try to keep the chunk count below a limit --optimize-min-chunk-size Minimal size for the created chunk --optimize-minimize Enable minimizing the output. Uses optimization.minimizer. [boolean] Stats options: --color, --colors Force colors on the console [boolean] [default: (supports-color)] --no-color, --no-colors Force no colors on the console [boolean] --sort-modules-by Sorts the modules list by property in module [string] --sort-chunks-by Sorts the chunks list by property in chunk [string] --sort-assets-by Sorts the assets list by property in asset [string] --hide-modules Hides info about modules [boolean] --display-exclude Exclude modules in the output [string] --display-modules Display even excluded modules in the output [boolean] --display-max-modules Sets the maximum number of visible modules in output [number] --display-chunks Display chunks in the output [boolean] --display-entrypoints Display entry points in the output [boolean] --display-origins Display origins of chunks in the output [boolean] --display-cached Display also cached modules in the output [boolean] --display-cached-assets Display also cached assets in the output [boolean] --display-reasons Display reasons about module inclusion in the output [boolean] --display-depth Display distance from entry point for each module [boolean] --display-used-exports Display information about used exports in modules (Tree Shaking) [boolean] --display-provided-exports Display information about exports provided from modules [boolean] --display-optimization-bailout Display information about why optimization bailed out for modules [boolean] --display-error-details Display details about errors [boolean] --display Select display preset [string] [choices: "", "verbose", "detailed", "normal", "minimal", "errors-only", "none"] --verbose Show more details [boolean] --info-verbosity Controls the output of lifecycle messaging e.g. Started watching files... [string] [choices: "none", "info", "verbose"] [default: "info"] --build-delimiter Display custom text after build output[string]
2,使用配置文件打包jquery
const path = require('path'); module.exports = { mode: "production", // "production" | "development" | "none" // Chosen mode tells webpack to use its built-in optimizations accordingly. entry: "./app/entry", // string | object | array // 這裏應用程序開始執行
//entry: ["./app/entry1", "./app/entry2"]
//entry: {
// a: "./app/entry-a",
// b: ["./app/entry-b", "./app/entry-b"]
// } // webpack 開始打包 output: { // webpack 如何輸出結果的相關選項 path: path.resolve(__dirname, "dist"), // string // 全部輸出文件的目標路徑 // 必須是絕對路徑(使用 Node.js 的 path 模塊) filename: "bundle.js", // string // 「入口分塊(entry chunk)」的文件名模板(出口分塊?) publicPath: "/assets/", // string // 輸出解析文件的目錄,url 相對於 HTML 頁面 library: "MyLibrary", // string, // 導出庫(exported library)的名稱 libraryTarget: "umd", // 通用模塊定義 // 導出庫(exported library)的類型 /* 高級輸出配置(點擊顯示) */ }, module: { // 關於模塊配置 rules: [ // 模塊規則(配置 loader、解析器等選項) { test: /\.jsx?$/, include: [ path.resolve(__dirname, "app") ], exclude: [ path.resolve(__dirname, "app/demo-files") ], // 這裏是匹配條件,每一個選項都接收一個正則表達式或字符串 // test 和 include 具備相同的做用,都是必須匹配選項 // exclude 是必不匹配選項(優先於 test 和 include) // 最佳實踐: // - 只在 test 和 文件名匹配 中使用正則表達式 // - 在 include 和 exclude 中使用絕對路徑數組 // - 儘可能避免 exclude,更傾向於使用 include issuer: { test, include, exclude }, // issuer 條件(導入源) enforce: "pre", enforce: "post", // 標識應用這些規則,即便規則覆蓋(高級選項) loader: "babel-loader", // 應該應用的 loader,它相對上下文解析 // 爲了更清晰,`-loader` 後綴在 webpack 2 中再也不是可選的 // 查看 webpack 1 升級指南。 options: { presets: ["es2015"] }, // loader 的可選項 }, { test: /\.html$/, test: "\.html$" use: [ // 應用多個 loader 和選項 "htmllint-loader", { loader: "html-loader", options: { /* ... */ } } ] }, { oneOf: [ /* rules */ ] }, // 只使用這些嵌套規則之一 { rules: [ /* rules */ ] }, // 使用全部這些嵌套規則(合併可用條件) { resource: { and: [ /* 條件 */ ] } }, // 僅當全部條件都匹配時才匹配 { resource: { or: [ /* 條件 */ ] } }, { resource: [ /* 條件 */ ] }, // 任意條件匹配時匹配(默認爲數組) { resource: { not: /* 條件 */ } } // 條件不匹配時匹配 ], /* 高級模塊配置(點擊展現) */ }, resolve: { // 解析模塊請求的選項 // (不適用於對 loader 解析) modules: [ "node_modules", path.resolve(__dirname, "app") ], // 用於查找模塊的目錄 extensions: [".js", ".json", ".jsx", ".css"], // 使用的擴展名 alias: { // 模塊別名列表 "module": "new-module", // 起別名:"module" -> "new-module" 和 "module/path/file" -> "new-module/path/file" "only-module$": "new-module", // 起別名 "only-module" -> "new-module",但不匹配 "only-module/path/file" -> "new-module/path/file" "module": path.resolve(__dirname, "app/third/module.js"), // 起別名 "module" -> "./app/third/module.js" 和 "module/file" 會致使錯誤 // 模塊別名相對於當前上下文導入 }, /* 可供選擇的別名語法(點擊展現) */ /* 高級解析選項(點擊展現) */ }, performance: { hints: "warning", // 枚舉 maxAssetSize: 200000, // 整數類型(以字節爲單位) maxEntrypointSize: 400000, // 整數類型(以字節爲單位) assetFilter: function(assetFilename) { // 提供資源文件名的斷言函數 return assetFilename.endsWith('.css') || assetFilename.endsWith('.js'); } }, devtool: "source-map", // enum // 經過在瀏覽器調試工具(browser devtools)中添加元信息(meta info)加強調試 // 犧牲了構建速度的 `source-map' 是最詳細的。 context: __dirname, // string(絕對路徑!) // webpack 的主目錄 // entry 和 module.rules.loader 選項 // 相對於此目錄解析 target: "web", // 枚舉 // 包(bundle)應該運行的環境 // 更改 塊加載行爲(chunk loading behavior) 和 可用模塊(available module) externals: ["react", /^@angular\//], // 不要遵循/打包這些模塊,而是在運行時從環境中請求他們 stats: "errors-only", // 精確控制要顯示的 bundle 信息 devServer: { proxy: { // proxy URLs to backend development server '/api': 'http://localhost:3000' }, contentBase: path.join(__dirname, 'public'), // boolean | string | array, static file location compress: true, // enable gzip compression historyApiFallback: true, // true for index.html upon 404, object for multiple paths hot: true, // hot module replacement. Depends on HotModuleReplacementPlugin https: false, // true for self-signed, object for cert authority noInfo: true, // only errors & warns on hot reload // ... }, plugins: [ // ... ], // 附加插件列表 /* 高級配置(點擊展現) */}
說明: webpack
1,運行配置文件,可在package.json下的`scripts`裏添加: { "build": "webpack --config webpack.config.js"},其中配置文件的默認名字爲webpack.config.js,若是是其餘名字能夠用config指認。es6
2,entry對象是webpack的打包的入口文件。webpack會根據entry的配置進行查找入口文件和全部依賴文件而且構建bundleweb
3,output對象指示webpack將如何去輸出,以及在哪裏輸出你的[bundle,asset和其餘你所打包或者使用wenbpack載入的任何內容]
3,webpack配合babel打包ES六、7
因爲ES6的普及和得心用手,幾乎全部項目中都會使用es6語法。可是瀏覽器對其支持並不友好,因此須要把es6降級到大部分瀏覽器都能解析的es5。babel就是這樣一個做用的工具。
babel-loader: 只是起到一個通知的角色,通知babel你須要幹活了,在webpack中是這樣的:
module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { // 這個配置項咱們通常單獨拿出來,建立一個‘.babelrc’文件來單獨存放配置項 presets: ['@babel/preset-env'],// babel預設 plugin: ['@babel/plugin-proposal-object-rest-spread'] // 所須要使用的插件 } } } }
若是說 babel-loader
是告訴webpack我要對js文件進行代碼兼容性編譯,那麼,webpack接下來就是要找babel,而bable的入口就是 babel-core
,只有經過它,webpack才能使用各類babel的api(前提是你安裝了相關的api)。
首先,介紹下歷史背景,對了解和學習 babel-preset-env 有幫助。
最初,爲了讓開發者可以儘早用上新的JS特性,babel團隊開發了babel-preset-latest。這個preset比較特殊,它是多個preset的集合(es2015+),而且隨着ECMA規範的更新更增長它的內容。
好比,當前(2018.06.02),它包含的preset包括:es201七、es101六、es2015。
到了明年,可能它包含的preset就包括:es201八、es201七、es201六、es2015。
隨着時間的推移,babel-preset-latest 包含的插件愈來愈多,這帶來了以下問題:
由於上述問題的存在,babel官方推出了babel-preset-env插件。它能夠根據開發者的配置,按需加載插件。配置項大體包括:
默認配置的狀況下,它跟 babel-preset-latest 是等同的,會加載從es2015開始的全部preset。
配置文件.babelrc以下,當前爲默認配置
{ "presets": [ "env" ] }
同時能夠針對node和瀏覽器版本去進行不一樣的配置,好比,咱們須要支持IE8+,chrome2+,那麼能夠這樣配置:
{ "presets": [ ["env", { "targets": { "browsers": [ "ie >= 8", "chrome >= 62" ] } }] ] }
預設只能將ES6語法編譯爲你指定的ES版本語法,例如:箭頭函數,可是像 Array.from
這樣的API呢他無能爲力。那麼,怎麼辦呢?
babel-polypill就是提供了es6新方法的解決方案,不過使用的時候是在入口文件全局引入,這樣會污染全局變量,因此須要babel-runtime,這樣就不要全局引入而致使全局變量的污染
{ "presets": [ ["env", { "targets": { "browsers": [ "ie >= 8", "chrome >= 62" ] } }] ], "plugins": ["transform-runtime"] // }