webpack多页面打包配置
单页面应用:整个应用里面只有一个html文件。现在主流的框架,vue,react都是单页面应用。
所以webpack绝大部分都是对单页面打包。那么webpack如何对多页面进行打包
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>html template</title> </head> <body> <div id='root'></div> </body> </html>
index.js
import React, {Component} from 'react'; import ReactDom from 'react-dom'; class App extends Component{ render() { return ( <div>this is home page</div> ) } } ReactDom.render(<App/>, document.getElementById('root'));
list.js
import React, {Component} from 'react'; import ReactDom from 'react-dom'; class App extends Component{ render() { return ( <div>this is list page</div> ) } } ReactDom.render(<App/>, document.getElementById('root'));
webpack.common.js
const plugins = [ // HtmlWebpackPlugin会在打包结束后,自动生成一个html文件,并把打包生成的js自动引入到这个html文件中 new HtmlWebpackPlugin({ template: 'src/index.html', filename: 'index.html', chunks: ['vendors', 'main'] }), new HtmlWebpackPlugin({ template: 'src/index.html', filename: 'list.html', chunks: ['vendors', 'list'] }), new CleanWebpackPlugin() ];
这里新建两个HtmlWebpackPlugin。HtmlWebpackPlugin是用来自动生成静态页面用的.模板是index.html,生成的文件名是index.html和list.html,里面植入的chunks分别是main和list。那么实际上多个页面就是多个HtmlWebpackPlugin