webpack深入了解——多入口、多出口以及html-webpack-plugin

1. 多个入口文件

如果有多个入口文件,该怎么办呢? 莫慌,我们可以将entry定义为一个数组,然后将需要打包的文件的路径依次写入,最终打好的包,就会按我们传入路径的顺序依次排列。

首先,在src目录下定义一个main2.js,然后在webpack.config.js文件当中,将entry属性改写一下,如下:

******webpack.config.js文件********

const path = require('path');
module.exports = {
    entry: ['./src/main.js', './src/main2.js'], //多入口的时候,这样写
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    }
    
}

然后,命令行运行 npm run build即可。

2. 多个出口文件

问题又来了,既然有多个入口的文件,那如果有多个出口的文件,怎么办呢? 其实,也简单,首先,我们的entry不能是一个数组了,因为数组和对象不一样,数组的每一个数据没有名字,所以我们首先要把entry改造成对象,如下:

const path = require('path');
module.exports = {
    entry: {     // 改造成对象之后,长这样。
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    }
    
}

到这里,好像还是多入口对应一个出口,我们还需要修改一下filename中的数据,我们可以写成这样filename:'[name].bundle.js',这里的[name]就好比是一个占位符,会把我们多个入口文件的名字替换到这里。最终,代码如下:

const path = require('path');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    }
    
}

最后,命令行运行npm run build

image.png

这时,打开index.html页面,什么也没有? 检查一下代码,发现我们引入的js有问题,,我们给写死了,难道需要我们手动写吗? 这会写疯的,还好我们webpack有插件的功能,这时我们就需要用到html-webpack-plugin这个插件了,注意,没有s,没有s,没有s,够三遍了吗?

3. html-webpack-plugin插件

我们最好是让dist目录自己创建,然后index.html也自己创建并且我们打包的多入口文件自动写好在index.html文件中,这个插件就可以帮我们实现这些。哇~

1. 首先,本地安装这个插件,npm i html-webpack-plugin -D

PS E:\goodStudy\webpackStudy> npm i html-webpack-plugin -D
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN [email protected] requires a peer of webpack@^1.0.0 || ^2.0.0 || ^3.0.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

+ [email protected]
added 7 packages from 4 contributors and audited 79 packages in 3.563s
found 0 vulnerabilities

然后,在webpack.config.js中导入这个模块,然后在plugins属性身上创建一个html-webpack-plugin的实例。

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin()
    ]
    
}

引入模块之后,接着就可以在命令行运行 npm run build了,好激动

PS E:\goodStudy\webpackStudy> npm run build

> [email protected] build E:\goodStudy\webpackStudy
> webpack --mode development

C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\bin\cli.js:231
                                throw err;
                                ^

Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at Object. (E:\goodStudy\webpackStudy\node_modules\html-webpack-plugin\lib\compiler.js:9:28)
    at Module._compile (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:178:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at Object. (E:\goodStudy\webpackStudy\node_modules\html-webpack-plugin\index.js:10:23)
    at Module._compile (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:178:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at Object. (E:\goodStudy\webpackStudy\webpack.config.js:2:27)
    at Module._compile (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:178:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at WEBPACK_OPTIONS (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\bin\convert-argv.js:115:13)
    at requireConfig (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\bin\convert-argv.js:117:6)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `webpack --mode development`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Administrator\AppData\Roaming\npm-cache\_logs\2019-08-17T09_48_59_104Z-debug.log

what the fuck!! Cannot find module 'webpack/lib/node/NodeTemplatePlugin'这句话好像是在说,我们没有本地安装webpack,好吧。

PS E:\goodStudy\webpackStudy> npm i webpack -D
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ [email protected]
added 346 packages from 197 contributors and audited 4304 packages in 47.673s
found 0 vulnerabilities

输入npm run build,又感觉好激动

> [email protected] build E:\goodStudy\webpackStudy
> webpack --mode development

One CLI for webpack must be installed. These are recommended choices, delivered as separate packages:
 - webpack-cli (https://github.com/webpack/webpack-cli)
   The original webpack full-featured CLI.
We will use "npm" to install the CLI via "npm install -D".
Do you want to install 'webpack-cli' (yes/no): yes

这里被提示,是否安装webpack-cli,我选的yes

要崩溃了,再次输入npm run build

PS E:\goodStudy\webpackStudy> npm run build

> [email protected] build E:\goodStudy\webpackStudy
> webpack --mode development

Hash: c2d4b4f7780fbf13548e
Version: webpack 4.39.2
Time: 542ms
Built at: 2019-08-17 5:59:56 PM
          Asset       Size  Chunks             Chunk Names
     index.html  249 bytes          [emitted]
 main.bundle.js   3.84 KiB    main  [emitted]  main
main2.bundle.js   3.82 KiB   main2  [emitted]  main2
Entrypoint main = main.bundle.js
Entrypoint main2 = main2.bundle.js
[./src/main.js] 76 bytes {main} [built]
[./src/main2.js] 49 bytes {main2} [built]
Child html-webpack-plugin for "index.html":
     1 asset
    Entrypoint undefined = index.html
    [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 472 bytes {0} [built]
    [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 497 bytes {0} [built]
        + 2 hidden modules

我擦,成功了,看一下index.html文件中的内容



  
    
    Webpack App
  
  
  

dist文件夹也是自动生成的,实现了我们的想法,虽然有些曲折

激动够了,又发现问题了,这个生成的index.html是个什么玩意儿,什么也没有啊,能不能定义一个模板之类的呢? 明确告诉大家,有。这需要用到,我们实例化的html-webpack-plugin这个对象了,我们实例了当然要有参数了,否则,他出来干啥?

1. 首先,这个实例有一个template属性,这个属性的值是一个模板的相对路径,注意是相对路径。

webpack.config.js文件:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({ // 老铁这样写,没毛病。
            template: './src/index.html'
        })
    ]
    
}

我们的src目录下的index.html,内容如下:




    
    
    
    hello world


    

命令行运行npm run build

dist文件夹中的index.html,内容如下:




    
    
    
    hello world


    

牛逼啊~,当然,还有更牛逼的,我们如果想要替换html页面中的title,可以这样做,首先,在webpack.config.js文件中给new的实例添加一个title属性,值就是你想要修改的title名,然后,页面中需要使用模板引擎来占位,格式是这样的<%=htmlWebpackPlugin.options.title %>,这样就可以定义页面的title了

webpack.config.js文件:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: '你好,世界',
            template: './src/index.html'
        })
    ]
    
}

src目录下的index.html文件:




    
    
    
     <%= htmlWebpackPlugin.options.title %> 


    

运行npm run builddist文件夹中的index.html内容如下:




    
    
    
     你好,世界 


    

世界如此的美好,

既然这个插件这么牛逼,有没有清缓存的功能呢? 有,直接在实例化的htmlWebpackPlugin身上添加一个hash:true,就搞定了,这样我们请求的js文件每次都需要重新加载。

webpack.config.js文件:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            hash: true, //清除浏览器加载文件的缓存
            title: '你好,世界',
            template: './src/index.html'
        })
    ]
    
}

dist目录下的index.html文件:





    
    
    
     你好,世界 



    

HtmlWebpackPlugin这个插件,还有压缩代码的功能,添加minify属性,这个属性当中有好多的配置,配置查阅地址。

例:

webpack.config.js文件当中添加minify属性

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            minify: {
                collapseWhitespace: true // 删除空格
            },
            hash: true,
            title: '你好,世界',
            template: './src/index.html'
        })
    ]
    
}

打包完成后,dist目录下的index.html文件,如下:

你好,世界

牛逼啊!!!

我又有一个问题,咱们上面这一顿操作,都是打包到了一个HTML页面中,能不能生成多个HTML文件呢?每个文件引用不同的模板,这能实现吗? 插件回复:只有你想不到,没有我做不到,这里需要用到filename这个属性,就是告诉webpack我要生成两个HTML文件,一个名字叫这个,另一个名字叫这个,这时,webpack就懂了。

我们先在src目录下创建一个index2.html的模板文件,然后webpack.config.js文件,如下:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename:'index.html',
            hash: true,
            title: '你好,世界',
            template: './src/index.html'
        }),

        new HtmlWebpackPlugin({
            filename:'index2.html',
            hash: true,
            title: 'hello world',
            template: './src/index2.html'
        })
    ]
    
}

打包完成之后,dist的目录,如下:

image.png

有了filename这个属性,我们想生成几个HTML文件都不是问题了,哇哈哈哈~

那个,我还有最后一个问题,如果我想让js文件分别打包到对应的HTML文件当中,怎么办呢? 好办,。可以通过chunks属性,来分别告诉实例对象,你只负责添加这个js文件就好,注意chunks是个数组。

webpack.config.js文件,如下:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            chunks: ['main'], // 这个名字,就是入口定义的名字
            filename:'index.html',
            hash: true,
            title: '你好,世界',
            template: './src/index.html'
        }),

        new HtmlWebpackPlugin({
            chunks:['main2'],
            filename:'index2.html',
            hash: true,
            title: 'hello world',
            template: './src/index2.html'
        })
    ]
    
}

dist目录下,index.html和index2.html文件,内容如下:

*********index.html**************




    
    
    
     你好,世界 


    
*********index2.html***********




    
    
    
     hello world 


    

最后,总结一下html-webpack-plugin插件中常用的配置:

  • template: '相对路径',作用:加载对应的模板文件;
  • title: '标题',作用:在页面中动态生成标题;
  • hash: true,作用:清除浏览器缓存,保证每次都加载最新的数据;
  • minify: {...},作用:压缩文件的操作;
  • filename: '生成的文件名',作用:用于定义生成多个HTML文件的文件名;
  • chunks: [入口文件名],作用:将对应的文件打入对应的HTML文件中。

你可能感兴趣的:(webpack深入了解——多入口、多出口以及html-webpack-plugin)