webpack4.x 入门一篇足矣

前言:

webpack4出了以后,一些插件变化很大,和之前的版本使用方式不一样,新手入坑,本篇将介绍如何从一开始配置webpack4的开发版本,对css,js进行编译打包合并生成md5,CSS中的图片处理,js自动注入html页,删除指定文件,提取公共文件热更新等等。

安装

//全局安装 
npm install -g webpack webpack-cli

创建文件夹初始化

//创建文件夹
mkdir webpack4demo
//进入
cd webpack4demo
//初始化
npm init -y

创建文件夹scripts 里面创建index.js文件

index.js

const s=()=>{ 
console.log('s init')
}
s()

创建webpack.config.js文件

webpack.config.js

const path = require("path");
module.exports = {
    entry: {
        index: "./scripts/index.js" //入口文件,若不配置webpack4将自动查找src目录下的index.js文件
    },
    output: {
        filename: "[name].bundle.js",//输出文件名,[name]表示入口文件js名
        path: path.join(__dirname, "dist")//输出文件路径
    }
}

执行webpack --mode development将会生成dist/index.bundle.js

创建index.html,并引入js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>$Title$</title>
</head>
<body>
$END$
</body>
<script src="./dist/index.bundle.js"></script> </html>

打开浏览器将会看到之前设置的js文件生效

对css,js进行编译打包合并生成md5

创建a.js,c.js,a.css,更改index.js

a.js

import acss from './a.css'
import c from './c.js'
const a={
    init(){
        console.log("a init bbbaaa") }, cinit(){ c.init() } } export default a;

c.js

const c={
    init(){
        console.log("ccccc")
    }
}
export default c;

a.css

body{ 
    background-color: #6b0392;
}

index.js

import a from './a.js'
import c from './c.js'
const s=()=>{
    a.init()
    a.cinit()
    c.init()
    console.log('s init')
}
s()

配置webpack.config.js文件

const path = require("path");
module.exports = {
    entry: {
        index: "./scripts/index.js"
    },
    output: {
        filename: "[name].bundle.[hash].js",//[hash]会在后面生成随机hash值 path: path.join(__dirname, "dist") }, module: { // 处理对应模块 rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ]//处理css } ] }, }

安装style-loader, css-loader

npm install style-loader css-loader --save-dev

执行webpack --mode development将会看到一个带md5值得js文件,将他引入html中

CSS中的图片处理

安装url-loader, file-loader

npm install url-loader file-loader --save-dev

修改a.css 将一张图片放到scripts目录

body{
    background-image: url("./timg.jpg");
    background-color: #a748ca;
}

配置webpack.config.js文件

module: {
    rules: [
        {
            test: /\.css$/,
            use: [ 'style-loader', 'css-loader' ]
        },
        {
            test:/\.(png|jpg|gif)$/,
            use:[{
                loader:'url-loader', options:{ outputPath:'images/',//输出到images文件夹 limit:500 //是把小于500B的文件打成Base64的格式,写入JS } }] } ] },

执行webpack --mode development将会看到dist中有一个images文件夹中有一张图片,打开index.html

js自动注入html文件

使用插件html-webpack-plugin,可以将生成的js自动引入html页面,不用手动添加

//安装html-webpack-plugin
npm install html-webpack-plugin --save-dev
//安装webpack webpack-cli
npm install webpack webpack-cli --save-dev

配置webpack.config.js文件

const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');//引入html-webpack-plugin
module.exports = {
    entry: {
        index: "./scripts/index.js"
    },
    output: {
        filename: "[name].bundle.[hash].js",
        path: path.join(__dirname, "dist") }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ] }, plugins: [// 对应的插件 new HtmlWebpackPlugin({ //配置 filename: 'index.html',//输出文件名 template: './index.html',//以当前目录下的index.html文件为模板生成dist/index.html文件 }), ] }

执行webpack --mode development 记得要讲之前手动引入的script删除,便可以看到dist那里自动生成一个index.html,打开便可以看到。

删除指定文件

使用插件clean-webpack-plugin,删除指定文件,更多配置,查看clean-webpack-plugin

npm install clean-webpack-plugin --save-dev

配置webpack.config.js文件

const CleanWebpackPlugin = require('clean-webpack-plugin');//引入    
plugins: [// 对应的插件
        new HtmlWebpackPlugin({ //配置
            filename: 'index.html',//输出文件名
            template: './index.html',//以当前目录下的index.html文件为模板生成dist/index.html文件
        }),
        new CleanWebpackPlugin(['dist']), //传入数组,指定要删除的目录
    ]

执行webpack --mode development,可以看到dist目录被删除,又生成一个新的dist,之前的js文件已经被删除。

提取公共文件

我们可看到a.js和index.js都引入了c.js文件,为什么要提取公共代码,简单来说,就是减少代码冗余,提高加载速度。和之前的webpack配置不一样:

//之前配置
// new webpack.optimize.SplitChunksPlugin({
//     name: 'common', // 如果还要提取公共代码,在新建一个实例
//     minChunks: 2, //重复两次之后就提取出来
//     chunks: ['index', 'a'] // 指定提取范围
// }),
//现在配置
optimization: {
    splitChunks: {
        cacheGroups: {
            commons: {  // 抽离自己写的公共代码
                chunks: "initial",
                name: "common", // 打包后的文件名,任意命名 minChunks: 2,//最小引用2次 minSize: 0 // 只要超出0字节就生成一个新包 }, vendor: { // 抽离第三方插件 test: /node_modules/, // 指定是node_modules下的第三方包 chunks: 'initial', name: 'vendor', // 打包后的文件名,任意命名 // 设置优先级,防止和自定义的公共代码提取时被覆盖,不进行打包 priority: 10 }, } } }, 

下载jq npm install jquery --save 在a.js,index.js引用 import $ from 'jquery' 输出$

生成3个js文件,执行webpack --mode development

热更新,自动刷新

我们将用到webpack-dev-servewebpack-dev-server就是一个基于Node.jswebpack的一个小型服务器,它有强大的自动刷新热替换功能。

安装webpack-dev-serve

npm install webpack-dev-serve --save-dev

配置webpack.config.js文件

const webpack = require("webpack");
plugins: [
    new HtmlWebpackPlugin({
        filename: 'index.html',
        template: './index.html',
    }),
    new CleanWebpackPlugin(['dist']), //传入数组,指定要删除的目录
    // 热更新,热更新不是刷新
    new webpack.HotModuleReplacementPlugin()
],
devServer: {//配置此静态文件服务器,可以用来预览打包后项目
    inline:true,//打包后加入一个websocket客户端 hot:true,//热加载 contentBase: path.resolve(__dirname, 'dist'),//开发服务运行时的文件根目录 host: 'localhost',//主机地址 port: 9090,//端口号 compress: true//开发服务器是否启动gzip等压缩 },

配置package.json

"scripts": {
  "dev": "webpack-dev-server --mode development"
},

执行npm run dev 访问 http://localhost:9090/

随便修改任一文件便会自动刷新网站显示修改相应内容。

总结:

webpack4还有很多很多配置,例如css的拆分呀,less sass配置呀,js编译es6呀,多入口配置呀,生产环境配置,js没有使用的模块自动检测剥离等等,只能等下次有空在总结,感谢大家的观看,新手入坑,欢迎指出错误的地方。

猜你喜欢

转载自www.cnblogs.com/kkdn/p/9233611.html