首頁  >  文章  >  web前端  >  webpack建構react多頁面

webpack建構react多頁面

巴扎黑
巴扎黑原創
2018-05-18 14:47:292479瀏覽

這篇文章主要介紹了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 (
   <p className="App">
    <p className="App-header">
     <h2>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

然後將index.js 中的內容替換為如下程式碼(刪除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;));

然後刪除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>
  <p id="root"></p>
 </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(&#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.然後用直接執行如下程式碼

npm run build

成功在dist中看到你的兩個頁面app1和app2.

如果要自行調試用直接啟用npm run start,然後在localhost:8181/app1.html查看頁面進行調試。

以上是webpack建構react多頁面的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn