首页 > 语言 > JavaScript > 正文

webpack4+react多页面架构的实现

2024-05-06 15:28:28
字体:
来源:转载
供稿:网友

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选