單頁面應用:整個應用里面只有一個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
