webpack 4.x (一)

在家第n天,想上班

webpack

零配置

touch webpack-demo
npm init [-y] 
npm install webpak webpack-cli -D
mkdir src
cd src
touch index.js

indexjs

console.log(1)

改变配置文件起始文件 main (据实际情况)

在这里插入图片描述

npx webpack

会生成dist/main.js 文件,运行它,打印结果 1

配置文件

默认配置文件取名
在这里插入图片描述
当然你也可以自定义文件名 mywebpack.js

npx webpack --config mywebpack.js

当然命令可以写在自定义script

  "scripts": {
    "build":"webpack --config mywebpack.js"
  },

运行

npm run build 

如果是默认的配置文件

  "scripts": {
    "build":"webpack "
  },
本地服务
npm install webpack-dev-server -D // 内存中启动本地服务
  "scripts": {
    "dev": "webpack-dev-server", 
    "build": "webpack"
  },

webpack.config.js

module.exports = {
    devServer: {
        port: 3333,
        progress: true, // 进度条
        contentBase: "./dist",
        open:true,
        compress:true, // gzip 压缩
    },
}

运行

npm run build 
html

webpack 打包默认识别js,打包js文件怎么跟html关联

npm install html-webpack-plugin -D // html插件

webpack.config.js

const path = require("path")
module.exports = {
    mode:"development",
    entry:'./src/index.js', // 单独模块引入
    output: {
        filename:"bundle.[hash:8].js",  // 打包后的文件[hash]
        path: path.resolve(__dirname,"dist"),// 路径绝对
    },
    devServer: {
        port: 3333,
        progress: true, // 进度条
        contentBase: "./dist",
        open:true,
        compress:true, // gzip 压缩
    },
    module:{ // 模块
    },
    plugins:[
        new HtmlWebpackPlugin({
            template: "./src/index.html",
            filename:"index.html",
            minify:{
                removeAttributeQuotes:true,//单双引号
                collapseWhitespace: true, // 折叠空行
            },
            hash:true,
        }),
    ]
}
解析css less
npm install  style-loader  css-loader -D //  css head style    css文件处理
npm install mini-css-extract-plugin -D // 抽离css样式文件
npm install postcss-loader autoprefixer  -D // css前缀  还需要配置文件
npm install optimize-css-assets-webpack-plugin -D //压缩css文件

webpack.config.js

const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin"); // html 模板
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // 分离css文件
const  optimizeCssAssets = require('optimize-css-assets-webpack-plugin');// 压缩css
module.exports = {
    mode:"development",
    entry:'./src/index.js', // 单独模块引入
    output: {
        filename:"bundle.[hash:8].js",  // 打包后的文件[hash]
        path: path.resolve(__dirname,"dist"),// 路径绝对
    },
    optimization:{ //优化项目
        minimizer:[
            new optimizeCssAssets(),
        ]
    },
    devServer: {
        port: 3333,
        progress: true, // 进度条
        contentBase: "./dist",
        open:true,
        compress:true, // gzip 压缩
    },
    module:{ // 模块
    	rules:[
    	            {
                test:/\.css$/, // 处理css
                 // use: [
                //     {
                //         loader:"style-loader",
                //         options:{
                //             insert: function insertAtTop(element) { // 官网案例  如果你在html head style 写相同样式 覆盖问题
                //                 var parent = document.querySelector('head');
                //                 // eslint-disable-next-line no-underscore-dangle
                //                 var lastInsertedElement =
                //                   window._lastElementInsertedByStyleLoader;
                 
                //                 if (!lastInsertedElement) {
                //                   parent.insertBefore(element, parent.firstChild);
                //                 } else if (lastInsertedElement.nextSibling) {
                //                   parent.insertBefore(element, lastInsertedElement.nextSibling);
                //                 } else {
                //                   parent.appendChild(element);
                //                 }
                //                 // eslint-disable-next-line no-underscore-dangle
                //                 window._lastElementInsertedByStyleLoader = element;
                //         }
                //     }
                //     },"css-loader"
                // ] 
                // 导出css文件
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader"
                ]
            },
            {
                test:/\.less$/, // 处理less
                use: [
                        MiniCssExtractPlugin.loader,"css-loader","less-loader","postcss-loader"
                ]  
            },]
    },
    plugins:[
        new HtmlWebpackPlugin({
            template: "./src/index.html",
            filename:"index.html",
            minify:{
                removeAttributeQuotes:true,//单双引号
                collapseWhitespace: true, // 折叠空行
            },
            hash:true,
        }),
       new MiniCssExtractPlugin({
            filename:"main.css"
        }),
    ]
}

postcss.config.js

module.exports = {
    plugins:[
        require("autoprefixer")
    ]
}
js ES6
// es6
npm install babel-loader @babel/core @babel/preset-env -D  //es6-es5  class报错,所以安装下个插件
npm install @babel/plugin-proposal-class-properties -D // 类插件
npm install @babel/plugin-proposal-decorators -D // 装饰器
npm install @babel/plugin-transform-runtime -D //部分高级语法不支持 补丁
npm install @babel/runtime - S
 npm install @babel/polyfill  -S // Babel 默认只转换新的 JavaScript 句法(syntax),而不转换新的 API,比如Iterator、Generator、Set、Map、Proxy、Reflect、Symbol、Promise等全局对象  补丁模块

npm install uglifyjs-webpack-plugin -D //压缩js文件
const uglifyjsPlugin = require("uglifyjs-webpack-plugin");

module.exports = {

    entry: ['@babel/polyfill', './src/index.js'], // 全觉  单文件使用 require('@babel/polyfill')
	......
	
    optimization:{ //优化项目
        minimizer:[
            new optimizeCssAssets(),
            new uglifyjsPlugin({
                cache:true,
                parallel:true,
                sourceMap: true
            })
        ]
    },
     module:{ 
            {
                test:/\.js$/,
                use:{
                    loader:"babel-loader",
                    options: { //
                        presets:[
                            "@babel/preset-env"
                        ],
                        plugins:[
                            ["@babel/plugin-proposal-decorators",{"legacy":true}],
                            ["@babel/plugin-proposal-class-properties",{"loose":true}],
                            "@babel/plugin-transform-runtime"
                        ]
                    }
                },
                include:path.resolve(__dirname,"src"),
                exclude:/node_modules/ // 排除哪些js
            },
	}
}
ESLINT
// js 校验
 npm install eslint eslint-loader -D // 还要去官网配置json文件
             {
                 test:/\.js$/,
                 use:{
                     loader:'eslint-loader',
                     options: {
                         enforce:'pre',
                     }
                 },
                 include:path.resolve(__dirname,"src"),
            },

依旧要有配置文件.eslintrc.json放在一级目录下

配置地址 官网

在这里插入图片描述

第三方全局变量

方法一

const webpack = require("webpack")

    plugins:[
  		...      
        new webpack.ProvidePlugin({
            $:"jquery" // 全局注入 每个文件
        })
    ]

方法二

npm install  expose-loader -D
rules: [
	     {  // 这种方法需要import  $ from 'jquery'
             test: require.resolve('jquery'),
              use:"expose-loader?$"
       },
]
图片
npm install file-loader -D
npm install html-withimg-loader -D // html模板插入图片,也是引用打包文件(一般不怎么用)
npm install url-loader -D // base64
rules:[ 
            { // 限制图片 在小于xx k base64 否则 自动交给file-loader
                test:/\.(png|jpg|jpeg|gif)$/,
                use:{
                    loader:"url-loader",
                    options:{
                        limit:200*1024,
                        outputPath:"/img/"
                    }
                }
            },
         ]

webpack.config.js

// eslint-disable-next-line no-undef
const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin"); // html 模板
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // 分离css文件
const  optimizeCssAssets = require('optimize-css-assets-webpack-plugin');// 压缩css
const uglifyjsPlugin = require("uglifyjs-webpack-plugin");
const webpack = require("webpack")

module.exports = {
    mode:"development",
    entry: ['@babel/polyfill', './src/index.js'], // 单独模块引入
    output: {
        filename:"bundle.[hash:8].js",  // 打包后的文件[hash]
        path: path.resolve(__dirname,"dist"),// 路径绝对
        pubilcPath:"http://www.xxx.com",// 比如配置cdn,会在所有资源路径下追加  
    },
    optimization:{ //优化项目
        minimizer:[
            new optimizeCssAssets(),
            new uglifyjsPlugin({
                cache:true,
                parallel:true,
                sourceMap: true
            })
        ]
    },
    devServer: {
        port: 3333,
        progress: true, // 进度条
        contentBase: "./dist",
        open:true,
        compress:true, // gzip 压缩
    },
    module:{ // 模块
        rules:[ // 规则 从右到左 从下往上
            {
                test: /\.html$/,
                use:"html-withimg-loader"
            },
            { // 限制图片 在小于xx k base64 否则 file-loader
                test:/\.(png|jpg|jpeg|gif)$/,
                use:{
                    loader:"url-loader",
                    options:{
                        limit:200*1024,
                        outputPath:"/img/"
                    }
                }
            },
            // {  // 这种方法需要import  $ from 'jquery'
            //     test: require.resolve('jquery'),
            //     use:"expose-loader?$"
            // },
            {
                test:/\.css$/, // 处理css

                // css style
                 // use: [
                //     {
                //         loader:"style-loader",
                //         options:{
                //             insert: function insertAtTop(element) { // 官网
                //                 var parent = document.querySelector('head');
                //                 // eslint-disable-next-line no-underscore-dangle
                //                 var lastInsertedElement =
                //                   window._lastElementInsertedByStyleLoader;
                 
                //                 if (!lastInsertedElement) {
                //                   parent.insertBefore(element, parent.firstChild);
                //                 } else if (lastInsertedElement.nextSibling) {
                //                   parent.insertBefore(element, lastInsertedElement.nextSibling);
                //                 } else {
                //                   parent.appendChild(element);
                //                 }
                //                 // eslint-disable-next-line no-underscore-dangle
                //                 window._lastElementInsertedByStyleLoader = element;
                //         }
                //     }
                //     },"css-loader"
                // ] 

                // 导出css文件
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader"
                ]
            },
            {
                test:/\.less$/, // 处理less
                use: [
                        MiniCssExtractPlugin.loader,"css-loader","less-loader","postcss-loader"
                ]  
            },
            {
                test:/\.js$/,
                use:{
                    loader:"babel-loader",
                    options: { //
                        presets:[
                            "@babel/preset-env"
                        ],
                        plugins:[
                            ["@babel/plugin-proposal-decorators",{"legacy":true}],
                            ["@babel/plugin-proposal-class-properties",{"loose":true}],
                            "@babel/plugin-transform-runtime"
                        ]
                    }
                },
                include:path.resolve(__dirname,"src"),
                exclude:/node_modules/ // 排除哪些js
            },
            // {
            //     test:/\.js$/,
            //     use:{
            //         loader:'eslint-loader',
            //         options: {
            //             enforce:'pre',
            //         }
            //     },
            //     include:path.resolve(__dirname,"src"),
            // },
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            template: "./src/index.html",
            filename:"index.html",
            minify:{
                removeAttributeQuotes:true,//单双引号
                collapseWhitespace: true, // 折叠空行
            },
            hash:true,
        }),
        new MiniCssExtractPlugin({
            filename:"main.css"
        }),
        new webpack.ProvidePlugin({
            $:"jquery" // 全局注入
        })
    ]
}

package.json

{
  "name": "webapck-demo",
  "version": "1.0.0",
  "description": "webpack-demo",
  "main": "./src/index.js",
  "scripts": {
    "dev": "webpack-dev-server",
    "build": "webpack"
  },
  "keywords": [
    "webpack"
  ],
  "author": "xx",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/plugin-proposal-class-properties": "^7.8.3",
    "@babel/plugin-proposal-decorators": "^7.8.3",
    "@babel/plugin-transform-runtime": "^7.8.3",
    "@babel/preset-env": "^7.8.4",
    "autoprefixer": "^9.7.4",
    "babel-loader": "^8.0.6",
    "css-loader": "^3.4.2",
    "eslint": "^6.8.0",
    "eslint-loader": "^3.0.3",
    "expose-loader": "^0.7.5",
    "file-loader": "^5.0.2",
    "html-webpack-plugin": "^3.2.0",
    "html-withimg-loader": "^0.1.16",
    "less": "^3.10.3",
    "less-loader": "^5.0.0",
    "mini-css-extract-plugin": "^0.9.0",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "postcss-loader": "^3.0.0",
    "style-loader": "^1.1.3",
    "uglifyjs-webpack-plugin": "^2.2.0",
    "url-loader": "^3.0.0",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.3"
  },
  "dependencies": {
    "@babel/polyfill": "^7.8.3",
    "@babel/runtime": "^7.8.4",
    "jquery": "^3.4.1"
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值