Webpack学习笔记

说明

这篇笔记是我学习lookroot在B站分享的Webpack教程的时候,对当时的配置文件进行了一个汇总,没办法,我真怕自己学完了也啥也不会。说来挺巧的,当时因为看到一些前端的招聘需求有Webpack,也不是什么太难的技术,那就补补课呗。结果一下午安装这玩意就搞了大半天,一步一个错,很多教程都很老了,Webpack最近更新之后变化很大,API都会变。没想到,这时候无意中发现了lookroot这个up主,就是就是最近一两天刚刚更新的教程,于是我立即学习起来,学了两遍吧,第一遍跟着做还一大堆bug,哭了。第二遍就还好5个小时左右就学完并且做完笔记了。在这里我分享一下它的教程链接,还有他的博客地址,希望对有需要的同学有帮助。

B站
博客

Webpack的安装

①快速初始化项目:cnpm init -y
②安装Webpack:cnpm i -D webpack
③安装Webpack-cli:cnpm i -D webpack-cli

项目打包

手动打包一个文件

.\node_modules\.bin\webpack  // 并未制定打包模式
npx webpack --mode development // 用开发者模式打包
    - 注意:npx是.\node_modules\.bin目录的简写

使用配置文件进行打包

配置文件:webpack.config.js

const path = require('path');


module.exports = {
    // 当前环境 开发环境 development 生产环境  production
    mode: "development",
    // 目标文件
    entry: [path.resolve(__dirname, './src/index.js')],
    // 输出文件
    output: {
        // 这里可以设置输出文件的路径和文件名
        path: path.resolve(__dirname, './dist'),
        filename: 'main.js'
    },
    // 插件
    plugins: [],
    // 模块规则
    module: {
        
    }
}

然后运行这个命令就可以直接进行打包:

npx webpack

设置快捷命令

package.json文件:

在script中可以任意添加快捷命令

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  }
}

然后就可以用这种命令打包了:

npm run dev
npm run build

多个目标和输出文件

注意:后面的所有小结我全部提供webpack.config.js和package.json两个文件。这个小结仅仅修改了webpack.config.js中的entry和output

webpack.config.js:

const path = require('path');


module.exports = {
    // 当前环境 开发环境 development 生产环境  production
    mode: "development",
    // 多个 目标文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 输出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [],
    // 模块规则
    module: {
        
    }
}

package.json

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  }
}

在Webpack中使用插件

html-webpack-plugin

作用:可以自动创建html文档,并且引入js文件

安装:

 cnpm i html-webpack-plugin -D

在webpack.config.js中导入和实例化插件

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    // 当前环境 开发环境 development 生产环境  production
    mode: "development",
    // 多个 目标文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 输出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [
        new HTMLWebpackPlugin({
            title: 'webpack demo'
        })
    ],
    // 模块规则
    module: {
        
    }
}

package.json

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  }
}

多页面项目

说明:就是自动生成html文档,并且不同的html文档分别引入不同的JavaScript文件。

同样是使用html-webpack-plugin插件

需要用html-webpack-plugin多实例化几个,并且增加filenamechunks等属性

webpack.config.js

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    // 当前环境 开发环境 development 生产环境  production
    mode: "development",
    // 多个 目标文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 输出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [
        new HTMLWebpackPlugin({
            filename: "index.html",
            title: "webpack demo",
            chunks: ['index']
        }),
        new HTMLWebpackPlugin({
            filename: "other.html",
            title: "webpack demo",
            chunks: ['other']
        })
    ],
    // 模块规则
    module: {
        
    }
}

package.json

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  }
}

sourcemap定位错误

作用:当代码出现bug时,由于已经进行打包无法定位原先在代码中的错误,这个配置就可以解决这个问题

主要是在配置文件中使用devtool这个配置

  • 开发环境可以使用cheap-module-eval-source-mapevaleval-source-map
  • 生产环境可以使用inline-source-mapinline-cheap-module-source-mapcheap-source-map

webpack.config.js

仅仅是在mode下面新增加了一个devtool配置

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    // 当前环境 开发环境 development 生产环境  production
    mode: "development",
    devtool: "cheap-module-eval-source-map",
    // 多个 目标文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 输出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [
        new HTMLWebpackPlugin({
            filename: "index.html",
            title: "webpack demo",
            chunks: ['index']
        }),
        new HTMLWebpackPlugin({
            filename: "other.html",
            title: "webpack demo",
            chunks: ['other']
        })
    ],
    // 模块规则
    module: {
        
    }
}

package.json

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  }
}

监听模式

作用:对代码进行修改并且保存之后,自动进行重新打包。但是在实际开发中并不是用的这种模式。

package.json

仅仅需要在package.json中添加一行脚本就行

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "watch": "webpack --mode development --watch"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  }
}

webpack.config.js

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    // 当前环境 开发环境 development 生产环境  production
    mode: "development",
    devtool: "cheap-module-eval-source-map",
    // 多个 目标文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 输出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [
        new HTMLWebpackPlugin({
            filename: "index.html",
            title: "webpack demo",
            chunks: ['index']
        }),
        new HTMLWebpackPlugin({
            filename: "other.html",
            title: "webpack demo",
            chunks: ['other']
        })
    ],
    // 模块规则
    module: {
        
    }
}

webpack-dev-server

作用:同样是在代码修改之后,自动进行打包,在通常的开发中都是使用这种模式

安装webpack-dev-server

cnpm i webpack-dev-server -D

在package.json中配置server命令

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "watch": "webpack --mode development --watch",
    "server": "webpack-dev-server --mode development"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  }
}

在webpack.config.js中配置devServer

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    // 当前环境 开发环境 development 生产环境  production
    mode: "development",
    devtool: "cheap-module-eval-source-map",
    // webpack-dev-server 的配置文件
    devServer: {
    /**
      * 日志模式  friendly-errors-webpack-plugin 插件可以优化输出
      * errors-only  只在发生错误时触发
      * minimal 只在发生错误或者有新的编译时输出
      * none 没有输出
      * normal 标准输出
      * verbose 全部输出
      */
        stats: "errors-only",
        //默认地址 localhost
        host: process.env.HOST,
        //默认端口 8080
        port: process.env.PORT,
        //是否直接打开浏览器
        open: true,
    },
    // 多个 目标文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 输出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [
        new HTMLWebpackPlugin({
            filename: "index.html",
            title: "webpack demo",
            chunks: ['index']
        }),
        new HTMLWebpackPlugin({
            filename: "other.html",
            title: "webpack demo",
            chunks: ['other']
        })
    ],
    // 模块规则
    module: {
        
    }
}

模块热更替

作用:之前,每次打包webpack就会把所有文件再次进行合并,如果项目过大,这个过程会非常消耗时间,使用模块热更替之后,每次修改文件也只会打包相应的文件。

这并不是一个插件,而是webpack内置的

webpack.config.js

导入webpack;在plugins中进行实例化,在devServer中配置hot。

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

module.exports = {
    // 当前环境 开发环境 development 生产环境  production
    mode: "development",
    devtool: "cheap-module-eval-source-map",
    // webpack-dev-server 的配置文件
    devServer: {
    /**
      * 日志模式  friendly-errors-webpack-plugin 插件可以优化输出
      * errors-only  只在发生错误时触发
      * minimal 只在发生错误或者有新的编译时输出
      * none 没有输出
      * normal 标准输出
      * verbose 全部输出
      */
        stats: "errors-only",
        //默认地址 localhost
        host: process.env.HOST,
        //默认端口 8080
        port: process.env.PORT,
        //是否直接打开浏览器
        open: true,
        hot: true
    },
    // 多个 目标文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 输出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [
        new HTMLWebpackPlugin({
            filename: "index.html",
            title: "webpack demo",
            chunks: ['index']
        }),
        new HTMLWebpackPlugin({
            filename: "other.html",
            title: "webpack demo",
            chunks: ['other']
        }),
        new webpack.HotModuleReplacementPlugin(),
        // 告诉你哪个文件发生了变化
        new webpack.NamedModulesPlugin()
    ],
    // 模块规则
    module: {
        
    }
}

package.json并未做任何修改

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "watch": "webpack --mode development --watch",
    "server": "webpack-dev-server --mode development"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  }
}

开发环境和生产环境分离

作用:在真实的开发环境中,肯定是平时使用一套配置,项目上线使用另一套配置。

安装插件

webpack-merge:自动将common分别和dev、prod配置文件进行合并

cnpm i webpack-merge -D

clean-webpack-plugin:自动删除之前打包的文件

cnpm i clean-webpack-plugin -D

新建三个配置文件:

①:webpack.common.js

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const {
    CleanWebpackPlugin
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');


module.exports = {
    entry: [
        path.resolve(__dirname, './src/index.js')
    ],
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ]
}

②:webpack.dev.js

const merge = require("webpack-merge")
const common = require("./webpack.common");

module.exports = merge(common, {
    mode: 'development',
    devtool: 'eval',
    devServer: {
        stats: "errors-only",
        //默认地址 localhost
        host: process.env.HOST,
        //默认端口 8080
        port: process.env.PORT,
        //是否直接打开浏览器
        open: true,
        hot: true
    }
})

③:webpack.prod.js

const merge = require("webpack-merge")
const common = require("./webpack.common");

module.exports = merge(common, {
    mode: "production"
})

package.json中配置新的命令

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "watch": "webpack --mode development --watch",
    "server": "webpack-dev-server --mode development",
    "envdev": "webpack-dev-server --config webpack.dev.js",
    "envbuild": "webpack --config webpack.prod.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0",
    "webpack-merge": "^4.2.2"
  }
}

项目启动

npm run envdev //用开发模式启动
npm run envbuild // 用生产模式启动项目

管理CSS

安装插件

cnpm i style-loader css-loader -D

配置文件,主要是webpack.dev.js中添加了模块规则

const merge = require("webpack-merge")
const common = require("./webpack.common");

module.exports = merge(common, {
    mode: 'development',
    devtool: 'eval',
    devServer: {
        stats: "errors-only",
        //默认地址 localhost
        host: process.env.HOST,
        //默认端口 8080
        port: process.env.PORT,
        //是否直接打开浏览器
        open: true,
        hot: true
    },
    module: {
        rules: [{
            test: /\.css$/,
            use:['style-loader', 'css-loader']
        }]
    }
})

其余两个配置文件均没有做任何修改

webpack.common.js

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const {
    CleanWebpackPlugin
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');


module.exports = {
    entry: [
        path.resolve(__dirname, './src/index.js')
    ],
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ]
}

webpack.prod.js

const merge = require("webpack-merge")
const common = require("./webpack.common");

module.exports = merge(common, {
    mode: "production"
})

使用一个js文件向index文件中注入内容

export default function divdoc(){
    let element = document.createElement("div");
    element.innerHTML = "webpack init";
    element.classList.add("init");
    document.body.appendChild(element);
}

CSS

.init {
    color: red;
    font-size: 48px;
}

index.js

import clg from './clg';
import divdoc from './js/divdoc';
import './css/app.css';

// console.log("webpack init");

clg('webpack init');
divdoc();

if(module.hot){
    module.hot.accept('./clg.js', () => {
        console.log("监听到clg.js文件修改")
    })
}

预处理

作用:配置完以后就可以将Less的代码转成CSS了

安装插件

①:less加载器

cnpm i less-loader -D

配置文件:

webpack.dev.js

主要是添加新的模块规则

const merge = require("webpack-merge")
const common = require("./webpack.common");

module.exports = merge(common, {
    mode: 'development',
    devtool: 'eval',
    devServer: {
        stats: "errors-only",
        //默认地址 localhost
        host: process.env.HOST,
        //默认端口 8080
        port: process.env.PORT,
        //是否直接打开浏览器
        open: true,
        hot: true
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use:['style-loader', 'css-loader']
            },
            {
                test: /\.less$/,
                use:['style-loader', 'css-loader', 'less-loader']
            }
        ]
    }
})

其余两个配置文件保持不变

webpack.common.js

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const {
    CleanWebpackPlugin
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');


module.exports = {
    entry: [
        path.resolve(__dirname, './src/index.js')
    ],
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ]
}

webpack.prod.js

const merge = require("webpack-merge")
const common = require("./webpack.common");

module.exports = merge(common, {
    mode: "production"
})

less文件

.init {
    color: red;
    font-size: 88px;
}

在index.js中导入less文件

import clg from './clg';
import divdoc from './js/divdoc';
import './css/app.less';
// import './css/app.css';

// console.log("webpack init");

clg('webpack init');
divdoc();

if(module.hot){
    module.hot.accept('./clg.js', () => {
        console.log("监听到clg.js文件修改")
    })
}

分离CSS

作用:之前的css处理都是直接插入到html文档的开头,但是如果样式非常多就必须被单独作为一个样式文件被引入进来

安装插件

①:迷你CSS提取器

cnpm i mini-css-extract-plugin -D

配置webpack.prod.js文件,主要是引入MiniCssExtractPlugin,然后进行实例化,配置模块规则

const merge = require("webpack-merge")
const common = require("./webpack.common");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = merge(common, {
    mode: "production",
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'style/[name].css'
        }),
    ],
    module: {
        rules: [
            {
                test: /\.css$/,
                use:[MiniCssExtractPlugin.loader, 'css-loader'] 
            }
        ]
    }
})

webpack.common.js

主要修改了入口这里的名字,这样导出之后的,css才会变成index.css,否则的话,默认是main.css

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const {
    CleanWebpackPlugin
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');


module.exports = {
    entry: 
        {
            index:path.resolve(__dirname, './src/index.js')
        }
    ,
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ]
}

webpack.dev.js

const merge = require("webpack-merge")
const common = require("./webpack.common");


module.exports = merge(common, {
    mode: 'development',
    devtool: 'eval',
    devServer: {
        stats: "errors-only",
        //默认地址 localhost
        host: process.env.HOST,
        //默认端口 8080
        port: process.env.PORT,
        //是否直接打开浏览器
        open: true,
        hot: true
    },
      
    module: {
        rules: [
            {
                test: /\.css$/,
                use:['style-loader', 'css-loader']
            },
            {
                test: /\.less$/,
                use:['style-loader', 'css-loader', 'less-loader']
            }
        ]
    }
})

其它内容文件

index.js

import clg from './clg';
import divdoc from './js/divdoc';
// import './css/app.less';
import './css/app.css';

// console.log("webpack init");

clg('webpack init');
divdoc();

if(module.hot){
    module.hot.accept('./clg.js', () => {
        console.log("监听到clg.js文件修改")
    })
}

app.css

.init {
    color: red;
    font-size: 48px;
}

管理图片

作用:主要是用来将某些比较小的图片就直接采用base64码的形式,减少内存消耗

安装插件

cnpm i file-loader -D
cnpm i url-loader -D

配置文件 webpack.common.js,主要是给图片添加一个模块规则

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const {
    CleanWebpackPlugin
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');


module.exports = {
    entry: 
        {
            index:path.resolve(__dirname, './src/index.js')
        }
    ,
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ],
    module: {
        rules: [
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        //超过这个大小,图片就打包为图片,不超过就打包为base64格式的代码
                        limit: 1000000,
                        //打包文件名
                        name: "img/[hash].[ext]",
                    },
                }
            },
        ]
    }
}

使用js文件插入背景图片

divdoc.js

import logo from "../assets/img/萌6.jpg"

export default function divdoc(){
    let element = document.createElement("img");
    element.src = logo;
    document.body.appendChild(element);
}

index.js

import clg from './clg';
import divdoc from './js/divdoc';
// import './css/app.less';
import './css/app.css';

// console.log("webpack init");

clg('webpack init');
divdoc();

if(module.hot){
    module.hot.accept('./clg.js', () => {
        console.log("监听到clg.js文件修改")
    })
}

管理资源路径

作用:真正的项目启动之后,可能资源并不在同一台服务器上,因此需要给各种资源配置合适的域名。

配置文件

webpack.common.js

主要修改了输出output时候的域名路径,其它配置文件请参考上面管理图片一节,是一样的。

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const {
    CleanWebpackPlugin
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');


module.exports = {
    entry: 
        {
            index:path.resolve(__dirname, './src/index.js')
        },
    output: {
        filename: "main.js",
        path: path.resolve(__dirname, 'dist'),
        publicPath: "https://www.lookrot.cn/assets"
    },
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ],
    module: {
        rules: [
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        //超过这个大小,图片就打包为图片,不超过就打包为base64格式的代码
                        limit: 10000000000000000,
                        //打包文件名
                        name: "img/[hash].[ext]",
                    },
                }
            },
        ]
    }
}

代码检查

安装eslint、loader、错误格式化插件

cnpm i eslint  eslint-loader eslint-friendly-formatter -D

新建配置文件.eslintrc.json

下面这段代码最后的rules就可以禁止在代码中使用 alert() 方法

{
    "env": {
        "browser": true,
        "es6": true,
        "node": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": 11,
        "sourceType": "module"
    },
    "rules": {
        "no-alert": 2
    }
}

webpack.dev.js 主要在模块规则里新增了语法检查的规则

const merge = require("webpack-merge")
const common = require("./webpack.common");
const path = require('path');


module.exports = merge(common, {
    mode: 'development',
    devtool: 'eval',
    devServer: {
        stats: "errors-only",
        //默认地址 localhost
        host: process.env.HOST,
        //默认端口 8080
        port: process.env.PORT,
        //是否直接打开浏览器
        open: true,
        hot: true
    },
      
    module: {
        rules: [
            {
                test: /\.css$/,
                use:['style-loader', 'css-loader']
            },
            {
                test: /\.less$/,
                use:['style-loader', 'css-loader', 'less-loader']
            },
            {
                test: /\.js$/,
                loader: 'eslint-loader',
                enforce: 'pre',
                include: [path.resolve(__dirname, 'src')],
                options: {
                    formatter: require('eslint-friendly-formatter')
                }
            }
        ]
    }
})

在 index.js 中故意写一个会出错的代码,也就是 alert()

import clg from './clg';
import divdoc from './js/divdoc';
// import './css/app.less';
import './css/app.css';

// console.log("webpack init");

clg('webpack init');
divdoc();

if(module.hot){
    module.hot.accept('./clg.js', () => {
        console.log("监听到clg.js文件修改")
    })
}

alert("test");

其它配置文件

webpack.common.js

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const {
    CleanWebpackPlugin
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');


module.exports = {
    entry: 
        {
            index:path.resolve(__dirname, './src/index.js')
        },
    output: {
        filename: "main.js",
        path: path.resolve(__dirname, 'dist'),
        // publicPath: "https://www.lookrot.cn/assets"
    },
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ],
    module: {
        rules: [
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        //超过这个大小,图片就打包为图片,不超过就打包为base64格式的代码
                        limit: 10000000000000000,
                        //打包文件名
                        name: "img/[hash].[ext]",
                    },
                }
            },
        ]
    }
}

webpack.prod.js

const merge = require("webpack-merge")
const common = require("./webpack.common");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = merge(common, {
    mode: "production",
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'style/[name].css'
        }),
    ],
    module: {
        rules: [
            // {
            //     test: /\.css$/,
            //     use:['style-loader', 'css-loader']
            // },
            // {
            //     test: /\.less$/,
            //     use:['style-loader', 'css-loader', 'less-loader']
            // }
            {
                test: /\.css$/,
                use:[MiniCssExtractPlugin.loader, 'css-loader'] 
            }
        ]
    }
})

babel代码转化

作用:将ES6及以上的代码,转化为ES5的代码,主要是考虑浏览器的兼容性

安装插件

cnpm i @babel/runtime -S
cnpm i  babel-loader  @babel/core @babel/preset-env @babel/plugin-transform-runtime -D

新建.babelrc配置文件

{
    "presets": [
        [
            "@babel/preset-env",
            {
                "useBuiltIns": "usage",
                "corejs": 3,
                "targets": {
                    "browsers": [ "ie >= 8", "chrome >= 62" ]
                }
            }
        ]
    ]
}

webpack.dev.js

主要添加了babel-loader模块规则

const merge = require("webpack-merge")
const common = require("./webpack.common");
const path = require('path');


module.exports = merge(common, {
    mode: 'development',
    devtool: 'eval',
    devServer: {
        stats: "errors-only",
        //默认地址 localhost
        host: process.env.HOST,
        //默认端口 8080
        port: process.env.PORT,
        //是否直接打开浏览器
        open: true,
        hot: true
    },
      
    module: {
        rules: [
            {
                test: /\.css$/,
                use:['style-loader', 'css-loader']
            },
            {
                test: /\.less$/,
                use:['style-loader', 'css-loader', 'less-loader']
            },
            {
                test: /\.js$/,
                loader: 'eslint-loader',
                enforce: 'pre',
                include: [path.resolve(__dirname, 'src')],
                options: {
                    formatter: require('eslint-friendly-formatter')
                }
            },
            {
                test: /\.js$/,
                use: [{
                    loader: 'babel-loader',
                }]
            }
        ]
    }
})

在index.js中写一个箭头函数

import clg from './clg';
import divdoc from './js/divdoc';
// import './css/app.less';
import './css/app.css';

// console.log("webpack init");

clg('webpack init');
divdoc();

if(module.hot){
    module.hot.accept('./clg.js', () => {
        console.log("监听到clg.js文件修改")
    })
}

alert("test");

// 可能写得不对
var say = () => {
    console.log("say");
}

say();
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,802评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,109评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,683评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,458评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,452评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,505评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,901评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,550评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,763评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,556评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,629评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,330评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,898评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,897评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,140评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,807评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,339评论 2 342