webpack学习记录(二-下)Plugin,SourceMap,WebpackDevServer, HMR

plugin : 可以在webpack运行到某个时刻的时候,帮你做一些事情

使用plugins让打包更便捷

HtmlWebpackPlugin :htmlWebpackPlugin 会在打包结束后,自动生成一个html文件,并把打包生成的js自动引入到这个html文件中

安装:npm i html-webpack-plugin -D

基本用法:在 webpack.config.js 中:

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

module.exports = {
  entry: 'index.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
    plugins: [new HtmlWebpackPlugin({
        template: 'src/index.html' //以index.html为模板,把打包生成的js自动引入到这个html文件中
    })]
};

CleanWebpackPlugin :自动清除上一次打包的dist文件

安装:npm i clean-webpack-plugin -D

基本用法:在 webpack.config.js 中:

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

module.exports = {
  entry: 'index.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
    plugins: [
        new HtmlWebpackPlugin({
        template: 'src/index.html' //在打包之后,以.html为模板,把打包生成的js自动引入到这个html文件中
    }),
        new CleanWebpackPlugin(['dist']), // 在打包之前,可以删除dist文件夹下的所有内容
    
    ]
};

Entry与Output的基础配置

在打包多入口文件时的配置

基本用法:在 webpack.config.js 中:

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

module.exports = {
  entry: {
       main: './src/index.js',
       sub: './src/index.js'
  },
  output: {
    publicPath: 'http://cdn.com.cn', //将注入到html中的js文件前面加上地址
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },
    plugins: [
        new HtmlWebpackPlugin({
        template: 'src/index.html' //在打包之后,以.html为模板,把打包生成的js自动引入到这个html文件中
    }),
        new CleanWebpackPlugin(['dist']), // 在打包之前,可以删除dist文件夹下的所有内容
    
    ]
};

详细请看官网:Output output-management

SourceMap 的配置

sourcemap:打包编译后的文件和源文件的映射关系,用于开发者调试用。

  • source-map 把映射文件生成到单独的文件,最完整但最慢
  • cheap-module-source-map 在一个单独的文件中产生一个不带列映射的Map
  • eval-source-map 使用eval打包源文件模块,在同一个文件中生成完整sourcemap
  • cheap-module-eval-source-map sourcemap和打包后的JS同行显示,没有映射列

    development环境推荐使用: devtool: 'cheap-module-eval-source-map',
    production环境推荐使用: devtool: 'cheap-module-source-map',

webpack.config.js

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

module.exports = {
    mode: 'development',
    devtool: 'cheap-module-eval-source-map',
    //devtool:'none',//在开发者模式下,默认开启sourcemap,将其关闭
    //devtool:'source-map'//开启映射打包会变慢
    //devtool:'inline-source-map'//不单独生成.map文件,会将生成的映射文件以base64的形式插入到打包后的js文件的底部
    //devtool:'cheap-inline-source-map'//代码出错提示不用精确显示第几行的第几个字符出错,只显示第几行出错,会提高一些性能
    //devtool:'cheap-module-inline-source-map'//不仅管自己的业务代码出错,也管第三方模块和loader的一些报错
    //devtool:'eval'//执行效率最快,性能最好,但是针对比较复杂的代码的情况下,提示内容不全面
    //devtool: 'cheap-module-eval-source-map',//在开发环境推荐使用,提示比较全,打包速度比较快
    //devtool: 'cheap-module-source-map',//在生产环境中推荐使用,提示效果会好一些
    
    
    entry: {
        main: './src/index.js'
    },
    module: {
        rules: [{
            test: /\.(jpg|png|gif)$/,
            use: {
                loader: 'url-loader',
                options: {
                    name: '[name]_[hash].[ext]',
                    outputPath: 'images/',
                    limit: 10240
                }
            } 
        }, {
            test: /\.(eot|ttf|svg)$/,
            use: {
                loader: 'file-loader'
            } 
        }, {
            test: /\.scss$/,
            use: [
                'style-loader', 
                {
                    loader: 'css-loader',
                    options: {
                        importLoaders: 2
                    }
                },
                'postcss-loader',
                'sass-loader',
                
            ]
        }]
    },
    plugins: [new HtmlWebpackPlugin({
        template: 'src/index.html'
    }), new CleanWebpackPlugin(['dist'])],
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist')
    }
}

详细请看官网:devtool

使用WebpackDevServer 提升开发效率

解决每次在src里编写完代码都需要手动重新运行 npm run dev

1.在 package.json 中配置

{
  "name": "haiyang",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "bundle": "webpack",
    "watch": "webpack --watch",// 加--watch自动监听代码的变化
    
  },
  
}

2.在 webpack.config.js 中,加 devServer

安装 npm i webpack-dev-server –D

  • contentBase :配置开发服务运行时的文件根目录
  • open :自动打开浏览器
  • host:开发服务器监听的主机地址
  • compress :开发服务器是否启动gzip等压缩
  • port:开发服务器监听的端口
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    mode: 'development',
    devtool: 'cheap-module-eval-source-map',
    entry: {
        main: './src/index.js'
    },
+    devServer: {
        contentBase: './dist',
        open: true,
        port: 8080,
        proxy: {//配置跨域,访问的域名会被代理到本地的3000端口
              '/api': 'http://localhost:3000'
        }
    },
    module: {
        rules: []
    },
    plugins: [],
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist')
    }
}

在 package.json 中:

{
  "name": "haiyang",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "bundle": "webpack",
    "watch": "webpack --watch",// 加--watch自动监听代码的变化
    "start": "webpack-dev-server",//配置热更新    
  }, 
}

详细请看官网 :dev-server

扩充知识:自己写一个类似webpackdevserver的工具

了解即可,功能不全,自行扩展。

在 package.json 中:

{
  "name": "haiyang",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "bundle": "webpack",
    "watch": "webpack --watch",// 加--watch自动监听代码的变化
    "start": "webpack-dev-server",//配置热更新
+    "server" : "node server.js" //自己写一个类似webpackdevserver的工具
  },
 
}

安装 :npm i express webpack-dev-middleware -D

在 server.js 中

const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const config = require('./webpack.config.js');
const complier = webpack(config);

const app = express();

app.use(webpackDevMiddleware(complier, {}));

app.listen(3000, () => {
    console.log('server is running');
});

模块热替换(hot module replacement)

在 package.json 中:

{
  "name": "haiyang",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server" //将文件打包到内存中,有助于开发
  },
}

在 webpack.config.js 中

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

module.exports = {
    mode: 'development',
    devtool: 'cheap-module-eval-source-map',
    entry: {
        main: './src/index.js'
    },
    devServer: {
        contentBase: './dist',
        open: true,
        port: 8080,
+        hot: true,//开启热更新
+        hotOnly: true//尽管html功能没有实现,也不让浏览器刷新
    },
    module: {
        rules: [{
            test: /\.(jpg|png|gif)$/,
            use: {
                loader: 'url-loader',
                options: {
                    name: '[name]_[hash].[ext]',
                    outputPath: 'images/',
                    limit: 10240
                }
            } 
        }, {
            test: /\.(eot|ttf|svg)$/,
            use: {
                loader: 'file-loader'
            } 
        }, {
            test: /\.scss$/,
            use: [
                'style-loader', 
                {
                    loader: 'css-loader',
                    options: {
                        importLoaders: 2
                    }
                },
                'postcss-loader',
                'sass-loader',
                
            ]
        }, {
            test: /\.css$/,
            use: [
                'style-loader',
                'css-loader',
                'postcss-loader'
            ]
        }]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html'
        }), 
        new CleanWebpackPlugin(['dist']),
+        new webpack.HotModuleReplacementPlugin() //使用模块热更新插件
    ],
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist')
    }
}

index.js

// 如果模块启用了HMR,就可以用 module.hot.accept(),监听模块的更新。
// vue中已经实现了该功能
if (module.hot) {
  module.hot.accept('./library.js', function() {
    // 使用更新过的 library 模块执行某些操作...
  })
}

注意点:

引入css,用框架Vue,React 时,不需要写 module.hot.accept(),因为在使用css-loader,vue-loader,babel-preset时,就已经配置好了HMR,不需要自己写

详细请看官方文档:hot-module-replacement api/hot-module-replacement concepts/hot-module-replacemen


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值