成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

Webpack包教不包會(huì)

gaara / 3005人閱讀

摘要:是什么本質(zhì)上,是一個(gè)現(xiàn)代應(yīng)用程序的靜態(tài)模塊打包器。當(dāng)處理應(yīng)用程序時(shí),它會(huì)遞歸地構(gòu)建一個(gè)依賴關(guān)系圖,其中包含應(yīng)用程序需要的每個(gè)模塊,然后將所有這些模塊打包成一個(gè)或多個(gè)。通過(guò)將選項(xiàng)設(shè)置為,啟用代碼壓縮和。

Webpack是什么?

本質(zhì)上,webpack 是一個(gè)現(xiàn)代 JavaScript 應(yīng)用程序的靜態(tài)模塊打包器(module bundler)。當(dāng) webpack處理應(yīng)用程序時(shí),它會(huì)遞歸地構(gòu)建一個(gè)依賴關(guān)系圖(dependency graph),其中包含應(yīng)用程序需要的每個(gè)模塊,然后將所有這些模塊打包成一個(gè)或多個(gè) bundle。 ——Webpack文檔

簡(jiǎn)單來(lái)說(shuō) Webpack就是一個(gè)前端項(xiàng)目的打包工具,精簡(jiǎn)一下就是:Webpack就是個(gè)工具

WebPack打包方式有什么特點(diǎn)?

WebPack以JavaScript為入口(entry);通過(guò)不同的loader,處理不同格式的資源(file資源file-loader/url-loader,css資源style-loader/css-loader,JavaScript資源babel-loader,等);通過(guò)html-webpack-plugin動(dòng)態(tài)生成html文件并插入CSS、JavaScript資源;通過(guò)output配置已經(jīng)處理過(guò)的文件,包括文件的名稱(filename)、生成文件放置位置(path)、線上資源服務(wù)路徑(publicPath),非入口文件名稱(chunkFilename)等。

WebPack的常用配置是什么?

entry WebPack的入口,打包入口文件的配置

output Webpack的出口,輸出打包后的文件配置

mode 配置的模式 development (開發(fā)模式) / production(生產(chǎn)模式) / none

module 模塊的處理方式 在這里使用各種loader處理不同的資源

plugins WebPack常用的一些插件 包括動(dòng)態(tài)生成Html,將CSS生成文件等等

devtool 調(diào)試方式 source-map等,

resolve 設(shè)置模塊如何被解析 alias 地址簡(jiǎn)寫 extensions 后綴自動(dòng)查找等

context: 基礎(chǔ)目錄,絕對(duì)路徑,用于從配置中解析入口起點(diǎn)(entry point)和 loader

WebPack的entry配置有幾種常用方式?

1 "./index.js"
2 {
     index: "./index.js"
 }
3 ["webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true", "./index.js"]
4 {
    index: ["webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true",
    , "./index.js"]
}

第二種常在打包生成上線文件時(shí)使用,第四種模式在多頁(yè)面需要進(jìn)行HMR時(shí),
第三種模式在進(jìn)行SPA頁(yè)面開發(fā)時(shí),或者在優(yōu)化多頁(yè)面HMR過(guò)程,HtmlWebpackPlugin生成Html文件比較耗時(shí),這時(shí)可以專注于當(dāng)前開發(fā)的頁(yè)面,即只打包當(dāng)前開發(fā)的頁(yè)面,減少需要重新生成的文件。

WebPack的output配置有幾種參數(shù)?

 output: {
        filename: "static/[name].js",
        path: path.resolve(__dirname, "dist"),
        publicPath: "/",
        chunkFileName: ""
    }

filename: 文件名稱 可以類似static/[name].js這樣書寫,可以增加一個(gè)static文件夾
path 輸出的路徑
publicPath 服務(wù)器防止資源文件的路徑
chunkFileName 非入口文件
WebPack的mode配置有幾種設(shè)置?

production development none

如果不設(shè)置,按照production方式

WebPack的常用module怎么配置?

module: {
    rules: [
        {
            test: /.css$/,
            use: [
                {
                    loader: MiniCssExtractPlugin.loader,
                    options: {
                        // you can specify a publicPath here
                        // by default it uses publicPath in webpackOptions.output
                        hmr: process.env.NODE_ENV === "development",
                    },
                },
                "css-loader"
            ]
        },
        {
            test: /.(png|jpg|gif|svg)$/,
            use: [
                {
                    loader: "file-loader",
                    options: {
                        name: "[name].[ext]",
                        outputPath: "images",
                    }
                }
            ]
        },
        {
            test: /.(woff|woff2|eot|ttf|otf)$/,
            use: [
                {
                    loader: "file-loader",
                    options: {
                        name: "[name].[ext]",
                        outputPath: "fonts"
                    }
                }
            ]
            {
            test: /.html$/,
            loader: [
                "html-loader"
            ]
        }
        }
    ]
}

還有bable-loader ,url-loader, postcss-loader,less-loader,vue-loader,sass-loader等等

WebPack的怎么動(dòng)態(tài)生成html并插入資源文件(css,js)?

return new HtmlWebpackPlugin({
            filename: `${fileName}.html`,
            template: "./template.html",
            inject: true,
            chunks: [`${fileName}`, "vendor"],
            minify: {
                collapseWhitespace: true,
                removeComments: true,
                useShortDoctype: true,
                trimCustomFragments: true,
                removeTagWhitespace: true,
                removeStyleLinkTypeAttributes: true,
                removeScriptTypeAttributes: true,
                removeRedundantAttributes: true
            }
   });

使用HtmlWebpackPlugin

WebPack怎么tree-shake?

使用 ES2015 模塊語(yǔ)法(即 import 和 export)。 確保沒(méi)有 compiler 將 ES2015 模塊語(yǔ)法轉(zhuǎn)換為CommonJS 模塊(這也是流行的 Babel preset 中 @babel/preset-env 的默認(rèn)行為 - 更多詳細(xì)信息請(qǐng)查看 文檔)。 在項(xiàng)目 package.json 文件中,添加一個(gè) "sideEffects" 屬性。 通過(guò)將 mode 選項(xiàng)設(shè)置為production,啟用 minification(代碼壓縮) 和 tree shaking。

WebPack怎么設(shè)置模塊熱更新?

devServer: {
        contentBase: "./dist",
        compress: true,
        hot: true
    },

使用webpack-dev-middlemare webpack-hot-middlemare
server端

const express = require("express");
const webpack = require("webpack");

const app = express();

const webpackConfig = require("./webpack.config");
const compiler = webpack(webpackConfig);

app.use(require("webpack-dev-middleware")(compiler, {
    noInfo: true,
    publicPath: webpackConfig.output.publicPath
}));

app.use(require("webpack-hot-middleware")(compiler));

app.listen(3000, () => {
    console.log(3000);
});

webpack entry配置

const hotMiddlewareScript = "webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true";

{
    index: ["hotMiddlewareScript",  "./index.js"]
}


Talk is cheap. Show me the code

安裝Webpack環(huán)境

mkdir learn-webpack && cd learn-webpack
npm init -y
npm install webpack webpack-cli --save-dev
touch webpack.config.js

webpack.config.js :

const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require("webpack");
const glob = require("glob");
const TerserJSPlugin = require("terser-webpack-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

const getEntries = () => {
    return glob
        .sync("src/**/*.js")
        .map(url => `./${url}`);
};

const getEntryNames = () => {
    const PRE_STR = "./src/";
    const entries = {};

getEntries()
    .forEach(url => {
        const removeExtUrl = url.replace(/.js$/ig, "");
        const fileParamsWithPath = removeExtUrl.slice(PRE_STR.length).split("/");
        entries[fileParamsWithPath.join("-")] = url.replace(/.js$/, "");
    });

return entries;
};

console.log(getEntryNames());

const getWebpackHtmls = () => {
    const PRE_STR = "./src/";

return getEntries()
    .map(url => {
        const removeExtUrl = url.replace(/.js$/ig, "");
        const fileParamsWithPath = removeExtUrl.slice(PRE_STR.length).split("/");
        const fileName = fileParamsWithPath.join("-");

        return new HtmlWebpackPlugin({
            filename: `${fileName}.html`,
            template: "./template.html",
            inject: true,
            chunks: [`${fileName}`, "vendor"],
            minify: {
                collapseWhitespace: true,
                removeComments: true,
                useShortDoctype: true,
                trimCustomFragments: true,
                removeTagWhitespace: true,
                removeStyleLinkTypeAttributes: true,
                removeScriptTypeAttributes: true,
                removeRedundantAttributes: true
            }
        });
    });
};

module.exports = {
    entry: getEntryNames(),
    output: {
        filename: "static/[name].js",
        path: path.resolve(__dirname, "dist"),
        publicPath: "/",
        chunkFilename: "static/vendor.js"
    },
    optimization: {
        minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
        splitChunks: {
            name: "vendor",
            chunks: "all",
            minChunks: 1
        }
    },
mode: "production",
module: {
    rules: [
        {
            test: /.css$/,
            use: [
                {
                    loader: MiniCssExtractPlugin.loader,
                    options: {
                        // you can specify a publicPath here
                        // by default it uses publicPath in webpackOptions.output
                        hmr: process.env.NODE_ENV === "development",
                    },
                },
                "css-loader"
            ]
        },
        {
            test: /.(png|jpg|gif|svg)$/,
            use: [
                {
                    loader: "file-loader",
                    options: {
                        name: "[name].[ext]",
                        outputPath: "images",
                    }
                }
            ]
        },
        {
            test: /.(woff|woff2|eot|ttf|otf)$/,
            use: [
                {
                    loader: "file-loader",
                    options: {
                        name: "[name].[ext]",
                        outputPath: "fonts"
                    }
                }
            ]

        },
        {
            test: /.html$/,
            loader: [
                "html-loader"
            ]
        }
    ]
},
plugins: [
    new CleanWebpackPlugin({
        dry: false,
        dangerouslyAllowCleanPatternsOutsideProject: true
    }),
    ...getWebpackHtmls(),
    new MiniCssExtractPlugin({
        // Options similar to the same options in webpackOptions.output
        // both options are optional
        filename: "style/[name].css",
        chunkFilename: "style/[id].css",
    }),
    new webpack.ProvidePlugin({
        join: ["lodash", "join"]
    })
],
resolve: {
    alias: {
        "@": path.resolve("./src")
    },
    extensions: [".js", ".jsx", ".css", ".less", ".json", "scss", ".vue"]
}
};

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/54167.html

相關(guān)文章

  • Webpack包教包會(huì)

    摘要:是什么本質(zhì)上,是一個(gè)現(xiàn)代應(yīng)用程序的靜態(tài)模塊打包器。當(dāng)處理應(yīng)用程序時(shí),它會(huì)遞歸地構(gòu)建一個(gè)依賴關(guān)系圖,其中包含應(yīng)用程序需要的每個(gè)模塊,然后將所有這些模塊打包成一個(gè)或多個(gè)。通過(guò)將選項(xiàng)設(shè)置為,啟用代碼壓縮和。 Webpack是什么? 本質(zhì)上,webpack 是一個(gè)現(xiàn)代 JavaScript 應(yīng)用程序的靜態(tài)模塊打包器(module bundler)。當(dāng) webpack處理應(yīng)用程序時(shí),它會(huì)遞歸地構(gòu)...

    harriszh 評(píng)論0 收藏0
  • 前端學(xué)習(xí)資源

    摘要:提供了完整的環(huán)境,并且支持自定義域名指向,動(dòng)態(tài)計(jì)算資源調(diào)整,可以完成各種應(yīng)用的開發(fā)編譯與部署。 react 新特性 react16 Context 算法相關(guān) 圖解排序算法(二)之希爾排序 微信小程序 微信小程序組件化的解決方案移動(dòng)端尺寸基本知識(shí) 瀏覽器 前端必讀:瀏覽器內(nèi)部工作原理瀏覽器緩存原理解讀瀏覽器加載css和js及dom解析之間的關(guān)系瀏覽器緩存 CSS學(xué)習(xí) 移動(dòng)web開發(fā)布局入...

    zhisheng 評(píng)論0 收藏0
  • 優(yōu)秀博文收藏(不定期更新)

    摘要:我的書簽我的書簽謹(jǐn)慎導(dǎo)入,小心覆蓋工具類版本管理快速切換源配置教程指南可視化工具前端工具集前端助手網(wǎng)絡(luò)封包截取工具格式化工具標(biāo)注工具模擬請(qǐng)求類深入淺出布局你所不知道的動(dòng)畫技巧與細(xì)節(jié)常用代碼黑魔法小技巧,讓你少寫不必要的,代碼更優(yōu)雅一勞永 我的書簽 我的書簽(謹(jǐn)慎導(dǎo)入,小心覆蓋) 工具類 nvm: node版本管理 nrm: 快速切換npm源 shell: zsh+on-my-zsh配...

    sunsmell 評(píng)論0 收藏0
  • 優(yōu)秀博文收藏(不定期更新)

    摘要:我的書簽我的書簽謹(jǐn)慎導(dǎo)入,小心覆蓋工具類版本管理快速切換源配置教程指南可視化工具前端工具集前端助手網(wǎng)絡(luò)封包截取工具格式化工具標(biāo)注工具模擬請(qǐng)求類深入淺出布局你所不知道的動(dòng)畫技巧與細(xì)節(jié)常用代碼黑魔法小技巧,讓你少寫不必要的,代碼更優(yōu)雅一勞永 我的書簽 我的書簽(謹(jǐn)慎導(dǎo)入,小心覆蓋) 工具類 nvm: node版本管理 nrm: 快速切換npm源 shell: zsh+on-my-zsh配...

    zhangfaliang 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<