• webpack进阶--打包


    上一片博文主要让大家了解下究竟webpack是干什么的,明显它是专注于打包的。


    gulp  和  webpack  的区别

    gulp,要求我们一步步写task(es6编译、css压缩、图片压缩、打包...),全过程都是我们掌控的(一开始项目小的时候,我们觉得灵活,但是后来项目复杂度上来了,我们觉得这样写task也太恶心了)。

    webpack,只要写好配置文件,就会帮我们处理好各种零散的html、css、js(这里包括它们的预编译语言例如jade、sass、es6、typescript等),然后打包成一个js文件。

    gulp和webpack最明显的区别就是webpack自动化程度更高,不用自己写各种各样的稀奇古怪的task。


    使用:

    1.安装

    webpack和gulp一样都要先全局安装一次,再在项目安装一次:

    npm i webpack -g
    npm i webpack -D

    ps:全局安装是为了能获取本地模块

    2.配置文件

    默认配置文件名:webpack.config.js

    如果想用其他名字例如:1.config 调用webpack时请用 webpack --config 1.config

    //webpack.config.js
    const path = require('path');
    //一个入口对一个最终打包的js
    //单入口写法
    module.exports = {
        entry: './src/script/main.js',
        output: {
            path: path.solve('./dist'),
            filename: 'bundle.js'
        }
    }
    -----------------------------------------------------------------------------------------------------
    //多个平行依赖入口写法,最终会打包在一起 module.exports = { entry: ['./src/script/main.js','./src/script/main2.js','./src/script/main3.js'], output: { path: path.solve('./dist'), filename: 'js/bundle.js' } }
    -----------------------------------------------------------------------------------------------------
    //多入口写法,最终会打包多个文件 //[name] 这里是page1 page2 //[hash] 这个每次打包生成的一个hash(签名)值 //[chunkhash] 这个是每个打包文件的md5 hash module.exports = { entry: { page1 :'./src/script/main.js', page2 :'./src/script/main2.js' }, output: { path: path.solve('./dist'), filename: 'js/[name]-[chunkhash].js' } }

    3.生成index.html(自动插入打包好的js文件)

    之前的文件都不能自动将打包文件放入index.html中,所以我们要借助新的插件html-webpack-plugin(需安装)

    //webpack.config.js
    const path = require('path');
    const htmlWebpackPlugin = require('html-webpack-plugin');
    module.exports = {
        entry: {
            a:'./src/script/main.js',
            b:'./src/script/main2.js'
        },
        output: {
            path: path.solve('./dist'),
            filename: 'js/bundle.js'
        },
        plugins:[
            new htmlWebpackPlugin({
                template: 'index.html', //以当前目录下的index.html为模板
                filename: 'index-[hash].html',
                inject: 'head',//默认时body
                hahaha: '自定义属性的自定义内容' ,//这个内容可以在模板上用ejs语法调用,例如<%=htmlWebpackPlugin.options.hahaha%>
                minify: { //压缩html
                    removeCommet: true, //去注释
                    collapseWhitespace: true //去空格
                },
                chunks:[a], //要入口js a
                excludeChunks:[b] //不要入口js b chunks和excludeChunks随便写一个就行
            })
        ]
    }
  • 相关阅读:
    vue-cli3 打包路径参数说明
    vuex使用map在module的模式下的写法
    普通的JS文件中使用vuex
    vue cli 3+ 版本的source map添加方法
    vue-cli的安装及版本查看/更新
    搭建一个vue项目
    无法将“vue”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
    Centos7开放及查看端口
    记录一次idae和maven设置的巨坑
    解决npm安装node-sass太慢及编译错误问题
  • 原文地址:https://www.cnblogs.com/amiezhang/p/8296554.html
Copyright © 2020-2023  润新知