>웹 프론트엔드 >JS 튜토리얼 >webpack 빌드는 다중 페이지에 반응합니다.

webpack 빌드는 다중 페이지에 반응합니다.

巴扎黑
巴扎黑원래의
2018-05-18 14:47:292602검색

这篇文章主要介绍了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 빌드는 다중 페이지에 반응합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.