從0開始配置webpack和搭建一個React項目

先來講說react搭建:
1 官方文檔上也有提供直接下載react包,可是修改webpack配置比較麻煩css

npx create-react-app my-app
cd my-app
npm start

修改webpack配置須要執行html

npm run eject

2 自行搭建一個項目而且配置webpack--主要記錄學習階段~總結的可能不太好,勉強看看,重點記錄一下第二種的方式node

經過yarn管理包
  1. 下載yarn

    yarn官網連接安裝步驟都有的react

  2. 在項目目錄下,執行yarn init

    會出現咱們的package.json文件
    圖片描述webpack

  3. 安裝webpack

    yarn add webpack --devweb

  4. 新建webpack.config.js文件,npm

    貼官網示例:json

    const path = require('path');
           module.exports = {
             entry: './src/app.js',
             output: {
               path: path.resolve(__dirname, 'dist'),
               filename: 'app.js'
             }
           };

    命令行執行webpack會發現dist目錄
    圖片描述
    注意:yarn安裝過程當中若是出錯,嘗試將yarn切換到淘寶鏡像再進行下載哦~,我安裝過程當中出現過問題,切到這就沒問題了
    yarn config set registry 'https://registry.npm.taobao.org'sass

  5. 安裝html-webpack-pluginbabel

    yarn add html-webpack-plugin --dev

文檔使用連接地址
按照文檔操做,修改webpack.config.js使用html-webpack-plugin打包html文件
再次執行webpack命令,會發現dist文件夾下面多了一個index.html
設置html-webpack-plugin的template模版,在src新建index.html,而且設置html內容

const path = require('path');
    var HtmlWebpackPlugin = require('html-webpack-plugin');
    module.exports = {
      entry: './src/app.js',
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'app.js'
      },
      plugins: [new HtmlWebpackPlugin(
        {
            template:'./src/index.html'
        }
      )]
    };

如今dist文檔下面的index.html就是當前src下的index.html的模版了

  1. 安裝babel

    yarn add babel-loader @babel/core @babel/preset-env

具體詳情見文檔地址 在src/app.js中寫入一些ES6語法,再次執行webpack命令,dist/app.js進行了轉換

  1. 安裝react轉換 babel-preset-react

    yarn add babel-preset-react --dev

    修改webpack.config.js

    const path = require('path');
       var HtmlWebpackPlugin = require('html-webpack-plugin');
       module.exports = {
         entry: './src/app.jsx'
           path: path.resolve(__dirname, 'dist'),
           filename: 'app.js'
         },
         plugins: [new HtmlWebpackPlugin(
           {
               template:'./src/index.html'
           }
         )],
         module: {
           rules: [
             {
               test: /\.m?jsx$/,
               exclude: /(node_modules|bower_components)/,
               use: {
                 loader: 'babel-loader',
                 options: {
                   presets: ['@babel/preset-env','react']
                 }
               }
             }
           ]
         }
       };
  2. 安裝react
    yarn add react react-dom
    react添加操做地址詳情
    將src/app.js修改成app.jsx

    import React from 'react';
       import ReactDOM from 'react-dom';
    
       ReactDOM.render(
         <h1>Hello, world!</h1>,
         document.getElementById('app')
       );

    再執行webpack進行打包
    若是出現Error: Plugin/Preset files are not allowed to export objects, only functions.錯誤

說明babel的版本不一致,我這邊是由於"babel-preset-react": "^6.24.1"默認裝的6版本,其餘babel安裝的是7版本,因此統一升級到7或者降級到6

yarn add babel-preset-react@7.0.0 --dev

這樣在進行打包,就能夠了,這個時候打開dist/index.html咱們看到hello, world!說成功編譯了react
圖片描述

  1. 安裝style-loader

    yarn add css-loader style-loader --dev
    安裝地址操做詳情
    在webpack.config.js的rules中添加

    {
       test: /\.css$/,
       use: ['style-loader', 'css-loader'],
     },

    在src下新建一個文件index.css,隨便修改一點樣式

    h1{
           color:#F00;
       }

    在app.jsx中引入

    import './index.css'

    再次執行webpack打包,刷新dist/index.html
    樣式應用上去了

  2. 安裝ExtractTextWebpackPlugin插件將css獨立到單獨的文件

    yarn add extract-text-webpack-plugin --dev

    官網連接地址

    const path = require('path');
       var HtmlWebpackPlugin = require('html-webpack-plugin');
       const ExtractTextPlugin = require("extract-text-webpack-plugin");
       module.exports = {
           entry: './src/app.jsx',
           output: {
               path: path.resolve(__dirname, 'dist'),
               filename: 'app.js'
           },
           module: {
               rules: [
               {
                   test: /\.m?jsx$/,
                   exclude: /(node_modules|bower_components)/,
                   use: {
                   loader: 'babel-loader',
                   options: {
                       presets: ['@babel/preset-env','react']
                   }
                   }
               },
               {
                   test: /\.css$/,
                   use: ExtractTextPlugin.extract({
                       fallback: "style-loader",
                       use: "css-loader"
                   })
               },
               ]
           },
           plugins: [
               new HtmlWebpackPlugin(
                   {
                       template:'./src/index.html'
                   }
               ),
               new ExtractTextPlugin("index.css"),
           ],
       };

    webpack.config.js配置如上
    再次執行webpack,dist目錄下就多了一個index.css了~
    注意:打包遇到Tapable.plugin is deprecated. Use new API on .hooks instead錯誤,緣由是extract-text-webpack-plugin目前版本不支持webpack4
    執行:yarn add extract-text-webpack-plugin@next --dev

  3. 安裝sass-loader

    yarn add sass-loader --dev

    在webpack.config.js中rules添加

    {
           test: /\.scss$/,
           use: ExtractTextPlugin.extract({
               fallback: 'style-loader',
               use: ['css-loader', 'sass-loader']
           })
       }

    新建一個index.scss文件

    body{
           background: #ccc;
           #app{
               font-size: 22px;
           }
       }

    在執行webpack會出現報錯Cannot find module 'node-sass'
    查看文檔連接
    須要安裝node-sass

    yarn add node-sass --dev

    打包,查看index.html能夠看到樣式應用上去了~
    圖片描述

  4. 安裝url-loader處理圖片連接

    yarn add url-loader file-loader --dev

    官網地址
    在rules中加入:

    {
           test: /\.(png|jpg|gif)$/i,
           use: [
             {
               loader: 'url-loader',
               options: {
                 limit: 8192
               }
             }
           ]
       }

    項目中引入圖片,進行打包,這樣圖片資源也打包解析進去了~

  5. 添加解析字體rule

    {
           test: /\.(eot|svg|ttf|woff|woff2|otf)$/i,
           use: [
               {
                 loader: 'url-loader',
                 options: {
                   limit: 8192,
                   name:'resource/[name].[ext]'
                 }
               }
           ]
       },
  6. 添加webpack-dev-server

    yarn add webpack-dev-server --dev

    修改package.json添加
    "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "watch": "webpack --watch",
    "start": "webpack-dev-server --open",
    "build": "webpack-cli"
    }
    執行yarn run start啓動項目

    yarn run build打包項目

    最後附上當前爲止修改後的webpack.config.js

    const path = require('path');
           const webpack = require('webpack');
           var HtmlWebpackPlugin = require('html-webpack-plugin');
           const ExtractTextPlugin = require("extract-text-webpack-plugin");
           module.exports = {
               entry: './src/app.jsx',
               output: {
                   path: path.resolve(__dirname, 'dist'),
                   filename: './js/[name].[hash].js',
                   chunkFilename: './js/[name].[hash].js',
               },
               devServer: {
                   port: 8080,
                   proxy: {
                       '/expo': {
                           target: 'https://xxx',
                           changeOrigin: true,
                           pathRewrite: {
                               '/expo': '/expo',
                           },
                           secure: false,
                       },
                   },
                   hot:true
               },
               module: {
                   rules: [
                   {
                       test: /\.m?jsx$/,
                       exclude: /(node_modules|bower_components)/,
                       use: {
                       loader: 'babel-loader',
                       options: {
                           presets: ['@babel/preset-env','react']
                       }
                       }
                   },
                   {
                       test: /\.css$/,
                       use: ExtractTextPlugin.extract({
                           fallback: "style-loader",
                           use: "css-loader"
                       })
                   },
                   {
                       test: /\.scss$/,
                       use: ExtractTextPlugin.extract({
                           fallback: 'style-loader',
                           use: ['css-loader', 'sass-loader']
                       })
                   },
                   {
                       test: /\.(png|jpg|gif|ico|jpeg)$/i,
                       use: [
                         {
                           loader: 'url-loader',
                           options: {
                               limit: 8192,
                               name: "[name].[ext]",
                               publicPath: "../images/",
                               outputPath: "images/"
                           }
                         }
                       ]
                   },
                   {
                       test: /\.(eot|svg|ttf|woff|woff2|otf)$/i,
                       use: [{
                           loader: "file-loader",
                           options: {
                             name: "[name].[ext]",
                             publicPath: "../fonts/",
                             outputPath: "fonts/"
                           }
                       }]
                   },
                   ]
               },
               plugins: [
                   new HtmlWebpackPlugin(
                       {
                           template:'./src/index.html'
                       }
                   ),
                   new ExtractTextPlugin("css/[name].css"),
               ],
               optimization:{
                   splitChunks:{
                       name:'common',
                       filename:'js/base.js'
                   }
               }
           };
相關文章
相關標籤/搜索