webpack在單頁面打包上應用廣泛,以create-react-app為首的腳手架眾多,單頁面打包通常是將業務js,css打包到同一個html文件中,整個項目只有一個html文件入口,但也有許多業務需要多個頁面不同的入口,比如不同的h5活動,或者需要支持seo的官方網站,都需要多個不同的html,webpack-react-multi-page架構讓你可以實現多頁面架構,在項目開發中保證每個頁面都可以熱更新并且打包后有清晰的文件層次結構。
Github地址
項目架構
技術使用
react16 webpack4 html-webpack-plugin 生成html文件 mini-css-extract-plugin css分離打包 uglifyjs-webpack-plugin js壓縮 optimize-css-assets-webpack-plugin css壓縮 es6 babel node opn 打開瀏覽器 compression 開啟gzip壓縮 express git目錄結構github
|-- webpack-react-multi-page //項目 |-- dist //編譯生產目錄 |-- index |-- index.css |-- index.js |-- about |-- about.css |-- about.js |-- images |-- index.html |-- about.html |-- node_modules //node包 |-- src //開發目錄 |-- index //index頁面打包入口 |-- images/ |-- app.js// index業務js |-- index.scss |-- index.js //index頁面js入口 |-- about //about頁面打包入口 |-- images/ |-- app.js// about業務js |-- index.scss |-- index.js //about頁面js入口 |-- template.html // html模板 |-- style.scss //公共scss |-- webpackConfig //在webpack中使用 |-- getEntry.js //獲取入口 |-- getFilepath.js //遍歷文件夾 |-- htmlconfig.js //每個頁面html注入數據 |-- package.json |-- .gitignore |-- webpack.config.js //webpack配置文件 |-- www.js //生產啟動程序
wiki
webpack單頁面打包配置
webpack.config.js
module.exports = (env, argv) => ({ entry: ".src/index.js", output: { path: path.join(__dirname, "dist"), filename: "bundle.js" }, module: { rules: [ ... ], }, plugins: [ new HtmlWebpackPlugin({ title: "首頁", filename:"index.html", favicon:"", template: "./src/template.html", }) ]});這樣就可以在dist文件夾下打包出一個下面這樣的文件
<!DOCTYPE html><html lang="en"> <head> <title>首頁</title> <body> <div id="root"></div> <script type="text/javascript" src="bundle.js"></script> </body></html>
webpack多頁面打包配置
webpack 的entry支持兩種種格式
打包單個文件
module.exports = { entry: '.src/file.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }};在dist下打包出一個bundle.js
新聞熱點
疑難解答
圖片精選