Prechádzať zdrojové kódy

tree shaking,code split,懒加载和预加载

DESKTOP-MK04A0R\chuck 3 rokov pred
rodič
commit
6b4c523e44

+ 1 - 0
22/build/css/built.7d59fc1ca3.css

@@ -0,0 +1 @@
+body,html{background:red;height:100%;margin:0;padding:0}

+ 1 - 0
22/build/index.html

@@ -0,0 +1 @@
+<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Document</title><script defer="defer" src="js/built.26216dee54.js"></script><link href="css/built.7d59fc1ca3.css" rel="stylesheet"></head><body><h1>hello chuck11222</h1></body></html>

Rozdielové dáta súboru neboli zobrazené, pretože súbor je príliš veľký
+ 0 - 0
22/build/js/built.26216dee54.js


Rozdielové dáta súboru neboli zobrazené, pretože súbor je príliš veľký
+ 0 - 0
22/build/js/built.26216dee54.js.map


+ 1 - 0
22/build/media/1feff74faa.bin

@@ -0,0 +1 @@
+__webpack_public_path__ = __webpack_base_uri__ = htmlWebpackPluginPublicPath;

+ 12 - 0
22/server.js

@@ -0,0 +1,12 @@
+/**
+ * 启动 node server.js
+ */
+const express =  require('express')
+
+const app = express()
+
+app.use(express.static('build',{ cacheControl: true, setHeaders: function(res, path) { 
+    res.setHeader("Cache-Control","max-age=3600");  
+}}));
+
+app.listen(3000)

+ 6 - 0
22/src/css/index.css

@@ -0,0 +1,6 @@
+html,body{
+    margin:0;
+    padding:0;
+    height:100%;
+    background:red;
+}

+ 12 - 0
22/src/index.html

@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Document</title>
+</head>
+<body>
+    <h1>hello chuck11222</h1>
+</body>
+</html>

+ 10 - 0
22/src/js/index.js

@@ -0,0 +1,10 @@
+import '../css/index.css';
+import { mul } from './test';
+
+function sum(...args) {
+  return args.reduce((p, c) => p + c, 0);
+}
+
+console.log(sum(1, 2, 3, 4, 5));
+
+console.log(mul(2, 3));

+ 6 - 0
22/src/js/test.js

@@ -0,0 +1,6 @@
+export function mul(x, y) {
+  return x * y;
+}
+export function count(x, y) {
+  return x - y;
+}

+ 150 - 0
22/webpack.config.js

@@ -0,0 +1,150 @@
+const { resolve } = require("path");
+//提取css
+const MiniCssExtractPlugin = require('mini-css-extract-plugin');
+//压缩css
+const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
+//js语法检查
+const EsLintPlugin = require('eslint-webpack-plugin')
+//html资源处理
+const HtmlWebpackPlugin = require('html-webpack-plugin')
+//设置node环境变量 postcss-loader会根据它读取package.js里的browserslist配置
+process.env.NODE_ENV = 'development'
+
+/**
+ * 去除无用代码
+ *      必须使用es6模块化
+ *      开启production环境
+ * 减少代码体积
+ * 
+ * 在package.json中配置
+ *      "sideEffects":false  所有代码都没有副作用,都可以进行tree shaking
+ *      可能会把css| @bable | polyfill 文件干掉
+ *      "sideEffects":["*.css","*.less"]  不会tree shaking
+ */
+//复用loader
+const commonCssLoader = [
+    MiniCssExtractPlugin.loader, //提取css
+    'css-loader',
+    {
+        loader: 'postcss-loader', //兼容性处理
+        options: {
+             // 旧版本配置
+            /* ident: 'postcss', 
+            plugins: () => [
+                require('postcss-preset-env')()  //读取package.json里browserslist配置,默认加载根据node_env加载production
+            ] */
+            postcssOptions: {
+                plugins: [
+                  [
+                    'postcss-preset-env'
+                  ],
+                ],
+            }
+        }
+    }
+]
+
+module.exports = {
+    entry: './src/js/index.js',
+    output: {
+        filename: 'js/built.[contenthash:10].js',
+        path: resolve(__dirname, 'build')
+    },
+    module:{
+        rules:[{
+            // 以下loader只会匹配一个 提高效率
+            // 注意:不能有两个配置处理同一种文件
+            oneOf:[
+                {
+                    test:/\.css$/,
+                    use: [
+                        ...commonCssLoader
+                    ]
+                },
+                {
+                    test:/\.less$/,
+                    use:[
+                        ...commonCssLoader,
+                        'less-loader'
+                    ]
+                },
+                {  //兼容性处理
+                    test:/\.js$/,
+                    exclude: /node_modules/,
+                    loader: 'babel-loader',
+                    options:{
+                        // 预设:指示babel做怎样的兼容性处理
+                        presets:[
+                            [
+                                '@babel/preset-env',
+                                {
+                                    useBuiltIns: 'usage',
+                                    corejs:{
+                                        version:3
+                                    },
+                                    targets:{
+                                        chrome: '60',
+                                        firefox: '60',
+                                        ie:'9',
+                                        safari: '10',
+                                        edge: '17'
+                                    }
+                                }
+                            ]
+                        ],
+                         //开启babel缓存
+                         // 第二次构建时,会读取之前的缓存
+                        cacheDirectory: true 
+                    }
+                },
+                //处理图片
+                {
+                    test:/\.(jpg|png|jpeg|gif)/,
+                    loader:'url-loader',
+                    options:{
+                        limit:8*1024,
+                        name:'[hash:10].[ext]',
+                        outputPath:'imgs',
+                        esModule: false,
+                    }
+                },
+                //html 处理
+                {
+                    test:/\.html$/,
+                    loader:'html-loader'
+                },
+                //其他资源处理
+                {
+                    exclude:/\.(js|css|less|html|jpg|jpeg|png|gif)/,
+                    loader:'file-loader',
+                    options:{
+                        outputPath:'media',
+                        esModule: false,
+                        name: '[hash:10].[ext]'
+                    },
+                    type: 'javascript/auto'
+                }
+            ]
+        }]
+    },
+    plugins:[
+        new MiniCssExtractPlugin({
+            filename: 'css/built.[contenthash:10].css'
+        }),
+        new OptimizeCssAssetsWebpackPlugin(),
+        new EsLintPlugin({
+            extensions: ['js', 'json', 'coffee'],
+            //exclude: '/node_modules/',
+            fix:true
+        }),
+        new HtmlWebpackPlugin({
+            template: './src/index.html',
+            minify:{
+                collapseWhitespace:true,
+                removeComments:true
+            }
+        })
+    ],
+    mode:'production',
+    devtool:'source-map'
+}

+ 1 - 0
23/build/index.html

@@ -0,0 +1 @@
+<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Document</title><script defer="defer" src="js/660.3a108e5d91.js"></script><script defer="defer" src="js/index.f690f431df.js"></script><script defer="defer" src="js/test.adb448127b.js"></script></head><body><h1>hello chuck11222</h1></body></html>

Rozdielové dáta súboru neboli zobrazené, pretože súbor je príliš veľký
+ 1 - 0
23/build/js/660.3a108e5d91.js


+ 24 - 0
23/build/js/660.3a108e5d91.js.LICENSE.txt

@@ -0,0 +1,24 @@
+/*!
+ * Sizzle CSS Selector Engine v2.3.6
+ * https://sizzlejs.com/
+ *
+ * Copyright JS Foundation and other contributors
+ * Released under the MIT license
+ * https://js.foundation/
+ *
+ * Date: 2021-02-16
+ */
+
+/*!
+ * jQuery JavaScript Library v3.6.0
+ * https://jquery.com/
+ *
+ * Includes Sizzle.js
+ * https://sizzlejs.com/
+ *
+ * Copyright OpenJS Foundation and other contributors
+ * Released under the MIT license
+ * https://jquery.org/license
+ *
+ * Date: 2021-03-02T17:08Z
+ */

+ 1 - 0
23/build/js/index.f690f431df.js

@@ -0,0 +1 @@
+(()=>{"use strict";var r,e={971:(r,e,o)=>{var n=o(660),a=o.n(n);console.log([1,2,3,4,5].reduce(((r,e)=>r+e),0)),console.log(a())}},o={};function n(r){var a=o[r];if(void 0!==a)return a.exports;var t=o[r]={exports:{}};return e[r].call(t.exports,t,t.exports,n),t.exports}n.m=e,r=[],n.O=(e,o,a,t)=>{if(!o){var l=1/0;for(u=0;u<r.length;u++){for(var[o,a,t]=r[u],i=!0,v=0;v<o.length;v++)(!1&t||l>=t)&&Object.keys(n.O).every((r=>n.O[r](o[v])))?o.splice(v--,1):(i=!1,t<l&&(l=t));if(i){r.splice(u--,1);var s=a();void 0!==s&&(e=s)}}return e}t=t||0;for(var u=r.length;u>0&&r[u-1][2]>t;u--)r[u]=r[u-1];r[u]=[o,a,t]},n.n=r=>{var e=r&&r.__esModule?()=>r.default:()=>r;return n.d(e,{a:e}),e},n.d=(r,e)=>{for(var o in e)n.o(e,o)&&!n.o(r,o)&&Object.defineProperty(r,o,{enumerable:!0,get:e[o]})},n.o=(r,e)=>Object.prototype.hasOwnProperty.call(r,e),(()=>{var r={826:0};n.O.j=e=>0===r[e];var e=(e,o)=>{var a,t,[l,i,v]=o,s=0;for(a in i)n.o(i,a)&&(n.m[a]=i[a]);if(v)var u=v(n);for(e&&e(o);s<l.length;s++)t=l[s],n.o(r,t)&&r[t]&&r[t][0](),r[l[s]]=0;return n.O(u)},o=globalThis.webpackChunk=globalThis.webpackChunk||[];o.forEach(e.bind(null,0)),o.push=e.bind(null,o.push.bind(o))})();var a=n.O(void 0,[660],(()=>n(971)));a=n.O(a)})();

+ 1 - 0
23/build/js/test.adb448127b.js

@@ -0,0 +1 @@
+(()=>{"use strict";var r,e={411:(r,e,o)=>{var a=o(660),n=o.n(a);console.log(n())}},o={};function a(r){var n=o[r];if(void 0!==n)return n.exports;var t=o[r]={exports:{}};return e[r].call(t.exports,t,t.exports,a),t.exports}a.m=e,r=[],a.O=(e,o,n,t)=>{if(!o){var l=1/0;for(u=0;u<r.length;u++){for(var[o,n,t]=r[u],i=!0,v=0;v<o.length;v++)(!1&t||l>=t)&&Object.keys(a.O).every((r=>a.O[r](o[v])))?o.splice(v--,1):(i=!1,t<l&&(l=t));if(i){r.splice(u--,1);var s=n();void 0!==s&&(e=s)}}return e}t=t||0;for(var u=r.length;u>0&&r[u-1][2]>t;u--)r[u]=r[u-1];r[u]=[o,n,t]},a.n=r=>{var e=r&&r.__esModule?()=>r.default:()=>r;return a.d(e,{a:e}),e},a.d=(r,e)=>{for(var o in e)a.o(e,o)&&!a.o(r,o)&&Object.defineProperty(r,o,{enumerable:!0,get:e[o]})},a.o=(r,e)=>Object.prototype.hasOwnProperty.call(r,e),(()=>{var r={43:0};a.O.j=e=>0===r[e];var e=(e,o)=>{var n,t,[l,i,v]=o,s=0;for(n in i)a.o(i,n)&&(a.m[n]=i[n]);if(v)var u=v(a);for(e&&e(o);s<l.length;s++)t=l[s],a.o(r,t)&&r[t]&&r[t][0](),r[l[s]]=0;return a.O(u)},o=globalThis.webpackChunk=globalThis.webpackChunk||[];o.forEach(e.bind(null,0)),o.push=e.bind(null,o.push.bind(o))})();var n=a.O(void 0,[660],(()=>a(411)));n=a.O(n)})();

+ 12 - 0
23/src/index.html

@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Document</title>
+</head>
+<body>
+    <h1>hello chuck11222</h1>
+</body>
+</html>

+ 16 - 0
23/src/js/index.js

@@ -0,0 +1,16 @@
+import $ from 'jquery'
+function sum(...args) {
+  return args.reduce((p, c) => p + c, 0);
+}
+
+console.log(sum(1, 2, 3, 4, 5));
+console.log($)
+
+// 通过js代码,让某个文件被单独打包成一个chunk 示例
+import ('./test')
+  .then((res)=>{
+    console.log(res)
+  })
+  .catch(()=>{
+    console.log('failed')
+  })

+ 8 - 0
23/src/js/test.js

@@ -0,0 +1,8 @@
+import $ from 'jquery'
+export function mul(x, y) {
+  return x * y;
+}
+export function count(x, y) {
+  return x - y;
+}
+console.log($)

+ 41 - 0
23/webpack.config.js

@@ -0,0 +1,41 @@
+const { resolve } = require("path");
+
+//html资源处理
+const HtmlWebpackPlugin = require('html-webpack-plugin')
+//设置node环境变量 postcss-loader会根据它读取package.js里的browserslist配置
+process.env.NODE_ENV = 'development'
+
+/**
+ * 1、通过多入口 + optimization配置
+ * 2、通过单入口 + optimization配置
+ * 3、通过js代码,让某个文件被单独打包成一个chunk 示例在 ./src/js/index.js
+ */
+module.exports = {
+    entry: {
+        // 多入口
+        index: './src/js/index.js',
+        test: './src/js/test.js'
+    },
+    output: {
+        // name取文件名
+        filename: 'js/[name].[contenthash:10].js',
+        path: resolve(__dirname, 'build')
+    },
+    plugins:[
+        new HtmlWebpackPlugin({
+            template: './src/index.html',
+            minify:{
+                collapseWhitespace:true,
+                removeComments:true
+            }
+        })
+    ],
+    // 可以将node_modules 中代码单独打包一个chunk最终输出
+    // 自动分析多入口chunk中,是否有公共文件,公共文件会单独打包。
+    optimization:{
+        splitChunks:{
+            chunks:'all'
+        }
+    },
+    mode:'production'
+}

+ 13 - 0
24/src/index.html

@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Document</title>
+</head>
+<body>
+    <h1>hello lazy loading</h1>
+    <button id="btn">按钮</button>
+</body>
+</html>

+ 12 - 0
24/src/js/index.js

@@ -0,0 +1,12 @@
+
+console.log('index.js加载')
+
+// import {mul} from './test'
+
+//懒加载  点击按钮时再加载test.js 不会重复加载
+document.getElementById("btn").onclick = function(){
+  //分割代码  webpackPrefetch:true 预加载:提前加载js文件
+  import(/* webpackChunkName: 'test',webpackPrefetch: true */'./test').then(({mul})=>{
+    console.log(mul(3,5))
+  })
+}

+ 8 - 0
24/src/js/test.js

@@ -0,0 +1,8 @@
+
+console.log('test.js加载')
+export function mul(x, y) {
+  return x * y;
+}
+export function count(x, y) {
+  return x - y;
+}

+ 33 - 0
24/webpack.config.js

@@ -0,0 +1,33 @@
+const { resolve } = require("path");
+
+//html资源处理
+const HtmlWebpackPlugin = require('html-webpack-plugin')
+//设置node环境变量 postcss-loader会根据它读取package.js里的browserslist配置
+process.env.NODE_ENV = 'development'
+
+/**
+ * 
+ */
+module.exports = {
+    entry:'./src/js/index.js',
+    output: {
+        // name取文件名
+        filename: 'js/[name].[contenthash:10].js',
+        path: resolve(__dirname, 'build')
+    },
+    plugins:[
+        new HtmlWebpackPlugin({
+            template: './src/index.html',
+            minify:{
+                collapseWhitespace:true,
+                removeComments:true
+            }
+        })
+    ],
+    optimization:{
+        splitChunks:{
+            chunks:'all'
+        }
+    },
+    mode:'production'
+}

+ 3 - 0
README.md

@@ -26,6 +26,9 @@ npx webpack serve
 * 19:source map 一种提供源代码到构建映射技术
 * 20: oneOf 只会匹配一个loader 提高效率
 * 21: 缓存
+* 22:tree shaking: 去除无用代码
+* 23: code split 代码分割
+* 24: 懒加载和预加载
 
 ## 关于
 用于学习webpack配置,包括css、less、图片资源、其他资源、开发环境等配置。

Niektoré súbory nie sú zobrazené, pretože je v týchto rozdielových dátach zmenené mnoho súborov