express製作小型熱載入打包webpack--react篇

劉勇大三入門前端發表於2021-01-03

node 伺服器的main.js檔案

var opn = require('opn') // 開啟瀏覽器
var path = require('path') // 路徑模組
var express = require('express') // express框架 
var webpack = require('webpack') //核心模組webpack

var webpackConfig = require('./webpack.config')// 配置檔案


var port = webpackConfig.devServer.port


var app = express()
var compiler = webpack(webpackConfig)

var devMiddleware = require('webpack-dev-middleware')(compiler, {
  publicPath: webpackConfig.output.publicPath,
//   quiet: true
})

var hotMiddleware = require('webpack-hot-middleware')(compiler, {
  log: false,
  heartbeat: 2000
})

app.use(require('connect-history-api-fallback')()) 
//開啟 支援history路由


app.use(devMiddleware) // 伺服器webpack外掛


app.use(hotMiddleware) // 熱載入自動打包


app.use('./static', express.static('./static'))

var uri = 'http://localhost:' + port

var _resolve
var readyPromise = new Promise(resolve => {
  _resolve = resolve
})

console.log('> Starting dev server...')
devMiddleware.waitUntilValid(() => {
  console.log('> Listening at ' + uri + '\n')
  
  if (process.env.NODE_ENV !== 'testing') {
    opn(uri)
  }
  _resolve()
})

var server = app.listen(port)

module.exports = {
  ready: readyPromise,
  close: () => {
    server.close()
  }
}

webpack配置檔案

const path=require("path")
const HtmlWebpackPlugin=require("html-webpack-plugin")//用於把HTML頁面放入記憶體
// const vueload=require("vue-loader/lib/plugin")
const minicss=require("mini-css-extract-plugin")//webpack4.0以後的打包css檔案
const optimizecssassetswebpackplugin=require("optimize-css-assets-webpack-plugin")//壓縮如果你使用ui元件庫已經壓縮的css就別必要了
const webpack = require("webpack")
const clernWebpackPlugin = require('clean-webpack-plugin')
const htmlplugin=new HtmlWebpackPlugin({
    template:path.join(__dirname,'./src/index.html'),//源標頭檔案
    filename:"index.html",//生成首頁的檔名稱
    minify: {
        removeAttributeQuotes: true,
        collapseWhitespace: true
    }
})
const css=new minicss({//輸出css獨立檔案
    filename:"./css/[name].css",
    chunkFilename:"[name].css"//或者id
})
module.exports={//webpack基於node構建的
    mode: "development", 
    entry: ['webpack-hot-middleware/client', './src/index.js'],  
    output: {
        filename: 'main.[hash:8].js',//通過熱載入輸出script檔案掛載在目錄與index.HTML一樣
        path: path.resolve(__dirname, 'dist')
    },
    watch: true,
    watchOptions:{
        poll:1000,
        // aggregateTimeOut: 500,
        ignored: /node_modules/
    },
    //production 提供了約定大於配置 約定打包檔案是src/index ->dist/main
    plugins:[
        htmlplugin,
    //    new vueload() ,
       css,
       new webpack.HotModuleReplacementPlugin()
    //    new clernWebpackPlugin('./dist')
     ],
    module: {//所以第三方模組的配置規則
        rules: [   
           
            {
                test: /\.js|.jsx$/,
                loader: 'babel-loader',
                exclude:/node_modules/
              },
              {
                test: /\.scss$/,
               
                
                use:[{loader:minicss.loader}, {
                    loader: 'css-loader',
                    options: { modules: true }
                  },'sass-loader']
              },
              {
                test: /\.tsx$/,
                loader: 'ts-loader',
                options: { appendTsSuffixTo: [/\.vue$/] },
                exclude:/node_modules/
              },
              {
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                  limit: 10000
                  
                }
              },
            // { test:/\.js|\jsx$/,use:[{loader:"babel-loader",options:{cacheDirectory:true}}],exclude:/node_modules/},//一個屬性use:"babel-loader"兩個是陣列
            // // { test:/\.css/,use:['style-loader','css-loader']},
            {test:/\.css$/,use:[{loader:minicss.loader},'css-loader']},
         //     { test:/\.scss/,use:['style-loader',  {loader: "css-loader",
         //     options: {//這個是react的css模組化
         //        modules: {
         //            localIdentName: "[path][name]-[local]-[hash:5]"
         //        }//import css from '路徑' console.log(css)會生成模組
         //        //這是react的處理辦法 vue就是style裡面寫scoped
         //        //支援id與class 控制檯輸出的模組是健對值形式
         //     }//css scss less一樣的配置模組化
         //    }]},
             { test:/\.(jpg|PNG|png|jpeg)/,use:[{loader:"url-loader",options:{
                 outputPath:"images/",
                 limit:1024,//單位是B 大於這個會打包出來
                 name:"[name].[ext]"
             }}]},                    
            //    { test:/.vue$/,use:[{loader:"vue-loader"}]},
               
           ]   
        },
        devtool:"source-map",//inline把js打包在一個檔案裡面 hidden分離出來 eval也是分離 
        // optimization:{//程式碼分割 下面vendors就是分割程式碼之後(把相同的庫或者檔案都提出來打包) 你可能在想css檔案去哪了 你登出程式碼分割 你可以看見css資料夾
        //     splitChunks:{
        //         chunks:"all"
        //     }
        // },
        resolve: {
            // 將 `.ts` 新增為一個可解析的副檔名。
            extensions: ['.js','.jsx','.tsx','.json']
        },
        devServer: {
            port: 8080,
            hot: true,
            grogress: true,
            historyApiFallback: true 
            //true 表示webpack支援使用history false路由預設是hash
        }   
}

執行的index.js檔案

import React from 'react'//建立元件虛擬dom 生命週期
import ReactDOM from 'react-dom'//把建立的元件虛擬dom放到頁面上展示的
import Router from './router/router'
import {store} from './redux/redux' // 只有index才預設選中 
import {Provider} from '../node_modules/react-redux'
//import 'react-hot-loader'; 沒有報錯可以註釋
import { hot } from 'react-hot-loader/root';
const App = () => <div>Hello World1!
        <Provider store={store}>
            <Router />,
        </Provider>,
</div>;
const Wpp = hot(App)
ReactDOM.render(
    <Wpp/>,
    document.getElementById("app")
)

babelrc

{
    "presets": ["env","stage-0","react"],
    "plugins": ["transform-runtime","react-hot-loader/babel"]
}

相關文章