• react + webpack 多页面搭建


    一、利用 creat-react-app 新建一个react单页面应用。

    cnpm i -g create-react-app

    create-react-app demo

    cd demo

    npm start

    可以看到下面页面

    三、修改index.js内容为:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.scss';
    
    class Login extends React.Component{
    
        constructor() {
            super();
            this.state = {
            }
        }
        componentDidMount(){
    
        }
    
        render() {
            return (
                <div className="login">
                    22
                  </div>
            )
        }
    }
    
    ReactDOM.render(
        <Login/>,
        document.getElementById('app')
    );

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

    现在src/下面有四个文件。接下来,在src下面新建自己需要的文件夹,分别将原来的四个文件拷贝进文件夹内。文件目录如下:

     五、修改public/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>

    六、开始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');
    
    let cssExtract = new ExtractTextPlugin('assets/css/reset.css');
    let sassExtract = new ExtractTextPlugin('assets/css/[name].[chunkhash:6].css');
    
    const env=process.argv[2];
    
    let dnsPath='';
    if(env==='pro'){
        dnsPath=''
    }else if(env==='stg'){
        dnsPath=''
    }else{//本地
        dnsPath='/finance/scan-to-pay'
    }
    
    const webpackConfig = {
      entry: {},
      output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'assets/js/[name].[chunkhash:6].js',
        publicPath: '/'
      },
      devServer: {
        host: "172.16.10.70",
        inline: true,
        port: 8181,
        // proxy: {
        //   '/financegateway': {
        //     target: '',
        //     changeOrigin: true
        //   }
        // }
        proxy: [{
          context: ['/financegateway', '/uploadimage', '/pointgate'],
          target: '',
          changeOrigin: true
        }]
      },
      module:{
        rules:[
          {
            test:/.js?$/,
            exclude:/node_modules/,
            loader:'babel-loader',
            query:{
              presets:['@babel/preset-env','@babel/preset-react']
            }
          },
          {
            test: /.css$/,
            use: cssExtract.extract({
              use: ['css-loader', 'postcss-loader']
            })
          },
          {
            test: /.scss$/, 
            loader: sassExtract.extract({
              use: ['css-loader', 'postcss-loader', 'sass-loader']
            })
          },
          // {
          //   test: /.(png|jpg|jpeg|gif)$/,
          //   use: [
          //     {
          //       loader: 'url-loader?limit=8192&name=assets/imgs/[name][hash:6].[ext]'
          //     }
          //   ]
          // }
          {
            test: /.(png|jpg|jpeg|gif|svg)$/,
            use: [
              {
                loader: 'file-loader',
                options: {
                  name() {
                    return 'assets/imgs/[hash:6].[ext]'
                  },
                  publicPath: '/'
                }
              }
            ]
          }
        ]
      },
      plugins: [
        cssExtract,
        sassExtract,
        new CleanWebpackPlugin(
          ['dist'],  
          {
            root: __dirname,              
            verbose: true,              
            dry:   false              
          }
        )
      ],
    };
    
    // 获取指定路径下的入口文件
    function getEntries(globPath) {
      const files = glob.sync(globPath),
       entries = {};
      files.forEach((filepath)=> {
        const path = filepath.replace(//index.js/, ''); // 获取文件路径
        let name = path.replace(/src//, ''); // 文件路径去除src目录
        entries[name] = './' + filepath;
      });
      return entries;
    }
        
    const entries = getEntries('src/**/index.js');
    
    // 循环入口文件
    Object.keys(entries).forEach((name)=> {
        webpackConfig.entry[name] = entries[name];
    
        const plugin = new HtmlWebpackPlugin({
          filename: `${name}/index.html`,
          template: `src/${name}/index.html`,
          inject: true,
          chunks: [name]
        });
        webpackConfig.plugins.push(plugin);
      
    })
    
    module.exports = webpackConfig;

    4.postcss.config.js

    module.exports = {
        plugins: [require('autoprefixer')({
            overrideBrowserslist: ["last 5 versions"] // 所有浏览器兼容到最后5个版本
        })]
    }

    开始install webpack和配置webpack

  • 相关阅读:
    javascript中无法通过div.style.left获取值的问题
    《Javascript高级程序设计第3版》精华总结
    前端面试笔试题回顾
    HTML 代码复用实践 (静态页面公共部分提取复用)
    将本地文件上传到远程库(二)
    ife-task0003学习收获总结
    将本地项目上传到git总结
    Minimum Size Subarray Sum —— LeetCode
    Binary Tree Preorder Traversal —— LeetCode
    Insertion Sort List —— LeetCode
  • 原文地址:https://www.cnblogs.com/hyshi/p/11536158.html
Copyright © 2020-2023  润新知