search
HomeWeb Front-endJS Tutorialwebpack builds react multi-page

webpack builds react multi-page

May 18, 2018 pm 02:47 PM
reactwebwebpack

This article mainly introduces the detailed explanation of building react multi-page applications with webpack. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

The original intention of writing this is that it is difficult to find a concise project scaffolding. Many scaffoldings have many dependencies, and it will take a long time just to look at the dependencies, so I refer to the content on the Internet and make it. Such a simple multi-page scaffolding.

Use creat-react-app to create a new react application

npm install -g create-react-app

Then create a project

create-react-app demo

create-react-app will automatically initialize a scaffolding And install various necessary dependencies of the React project. If there are network problems during the process, please use the cnpm Taobao mirror to install.

Then we enter the project and start it.

cd demo

Then start the project

npm start

You will see the following page


Then enter src/App.js, Replace the code in App.js with the following code (because you don’t want to process images and icons in webpack for the time being)

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

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

export default App

Then replace the content in index.js with the following code (delete registerServiceWorker)

import React from &#39;react&#39;;
import ReactDOM from &#39;react-dom&#39;;
import &#39;./index.css&#39;;
import App from &#39;./App&#39;;


ReactDOM.render(<App />, document.getElementById(&#39;root&#39;));

Then delete registerServiceWorker.js under src (this file is used to build pwa applications, we can’t use it for the time being) and logo.svg files (you don’t want to process image files) and App.test.js (for testing) .

There are four files under src/ now. Next, create two new folders app1 and app2 under src, and copy the original four files into app1 and app2 respectively. The file directory is as follows:


Next, go to the public file, delete favicon.ico (don’t want to deal with it) and manifest.json (used to build pwa), and then Replace the content in index.html with the following content

<!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>
  <p id="root"></p>
 </body>
</html>

This index.html is our template html.

Get to the point and start installing webpack and configuring webpack

1. Install dependencies. Replace the package.json file with the following file

{
 "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. Delete node_modules in the current directory, and then execute it on the console again

npm i

3. In the root directory, which is /demo Create a new webpack.config.js file and write the following code

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

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

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

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

module.exports = webpackConfig;

4. Then directly execute the following code

npm run build

to successfully see your two pages app1 and app2 in dist.

If you want to debug by yourself, just enable npm run start, and then view the page for debugging at localhost:8181/app1.html.

The above is the detailed content of webpack builds react multi-page. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools