webpack构建react多页面应用详解

时间:2019-04-06
本文章向大家介绍webpack构建react多页面应用详解,主要包括webpack构建react多页面应用详解使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

写这个的初衷是很难找一个简洁的项目脚手架,很多脚手架都有很多依赖,光看依赖就要很久,所以自己参照网上的内容,弄个这么一个简单的多页面的脚手架。

利用creat-react-app 新建一个react应用

npm install -g create-react-app

然后创建一个项目

create-react-app demo

create-react-app会自动初始化一个脚手架并安装 React 项目的各种必要依赖,如果在过程中出现网络问题,请用cnpm淘宝镜像安装。

然后我们进入项目并启动。

cd demo

然后启动项目

npm start

那就会看到如下页面


然后进入src/App.js,用下面代码替换App.js中的代码(因为在webpack中暂时不想处理图片和icon)

import React, { Component } from 'react';
import './App.css';

class App extends Component {
 render() {
  return (
   <div className="App">
    <div className="App-header">
     <h2>Welcome to App</h2>
    </div>
    <p className="App-intro">
     To get started, edit <code>src/App.js</code> and save to reload.
    </p>
   </div>
  );
 }
}

export default App

然后将 index.js 中的 内容替换为如下代码(删除registerServiceWorker)

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';


ReactDOM.render(<App />, document.getElementById('root'));

然后删除src下面的registerServiceWorker.js(该文件用于构建pwa应用用的,暂时我们用不了)和 logo.svg文件(不想处理图片文件)和 App.test.js(用于测试用的)。

现在src/下面有四个文件。接下来,在src下面新建两个文件夹 app1和 app2,分别将原来的四个文件拷贝进入app1和app2。文件目录如下:


接下来,进入public文件下,删除favicon.ico(不想处理)和 manifest.json(构建pwa用的),然后将index.html中的内容用如下内容替换

<!doctype html>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="theme-color" content="#000000">
  <title>React App</title>
 </head>
 <body>
  <noscript>
   You need to enable JavaScript to run this app.
  </noscript>
  <div id="root"></div>
 </body>
</html>

这个index.html就是我们的模版html。

进入正题,开始install webpack和配置webpack

1.安装依赖。将package.json文件用下面的文件替代

{
 "name": "demo",
 "version": "0.1.0",
 "private": true,
 "dependencies": {
  "react": "^15.6.1",
  "react-dom": "^15.6.1"
 },
 "devDependencies": {
  "babel-core": "^6.26.0",
  "babel-loader": "^7.1.2",
  "babel-preset-es2015": "^6.24.1",
  "babel-preset-react": "^6.24.1",
  "clean-webpack-plugin": "^0.1.16",
  "css-loader": "^0.28.7",
  "extract-text-webpack-plugin": "^3.0.0",
  "file-loader": "^1.0.0",
  "glob": "^7.1.2",
  "html-webpack-plugin": "^2.30.1",
  "postcss-loader": "^2.0.6",
  "style-loader": "^0.18.2",
  "url-loader": "^0.5.9",
  "webpack": "^3.5.6",
  "webpack-dev-server": "^2.8.1"
 },
 "scripts": {
  "start": "webpack-dev-server --open",
  "build": "webpack"
 }
}

2.删除当前目录中的node_modules,然后重新在控制台执行

npm i 

3.在根目录下也就是/demo下新建一个webpack.config.js文件,写入如下代码

const webpack = require('webpack');
const glob = require('glob');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

const webpackConfig = {
  entry: {},
  output:{
    path:path.resolve(__dirname, './dist/'),
    filename:'[name].[chunkhash:6].js'
  },
  //设置开发者工具的端口号,不设置则默认为8080端口
  devServer: {
    inline: true,
    port: 8181
  },
  module:{
    rules:[
      {
        test:/\.js?$/,
        exclude:/node_modules/,
        loader:'babel-loader',
        query:{
          presets:['es2015','react']
        }
      },
      {
        test: /\.(scss|sass|css)$/, 
        loader: ExtractTextPlugin.extract({fallback: "style-loader", use: "css-loader"})
      },
      
    ]
  },
  plugins: [
    new ExtractTextPlugin("[name].[chunkhash:6].css"),
    new CleanWebpackPlugin(
      ['dist'],  
      {
        root: __dirname,              
        verbose: true,              
        dry:   false              
      }
    )
  ],
};

// 获取指定路径下的入口文件
function getEntries(globPath) {
  const files = glob.sync(globPath),
   entries = {};
  files.forEach(function(filepath) {
    const split = filepath.split('/');
    const name = split[split.length - 2];
    entries[name] = './' + filepath;
  });
  return entries;
}
    
const entries = getEntries('src/**/index.js');

Object.keys(entries).forEach(function(name) {
  webpackConfig.entry[name] = entries[name];
  const plugin = new HtmlWebpackPlugin({
    filename: name + '.html',
    template: './public/index.html',
    inject: true,
    chunks: [name]
  });
  webpackConfig.plugins.push(plugin);
})

module.exports = webpackConfig;

4.然后用直接执行如下代码

npm run build

成功在dist中看到你的两个页面app1和app2.

如果要自己调试用直接启用npm run start,然后在localhost:8181/app1.html查看页面进行调试。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。