express製作小型熱載入打包webpack

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

json檔案執行配置

"scripts": {
    "dev": "node index.js"
  },

index.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')())


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配置檔案
entry: [‘webpack-hot-middleware/client’, ‘./src/index.js’],

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$/,
                loader: 'babel-loader',
                exclude:/node_modules/
              },
              {
                test: /\.scss$/,
                // use: [
                //   'vue-style-loader',
                //   'css-loader',
                //   'sass-loader'
                // ]
                
                use:[{loader:minicss.loader}, {
                    loader: 'css-loader',
                    options: { modules: true }
                  },'sass-loader']
              },
              {
                test: /\.ts$/,
                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:"hidden-source-map",//inline把js打包在一個檔案裡面 hidden分離出來 eval也是分離 
        optimization:{//程式碼分割 下面vendors就是分割程式碼之後(把相同的庫或者檔案都提出來打包) 你可能在想css檔案去哪了 你登出程式碼分割 你可以看見css資料夾
            splitChunks:{
                chunks:"all"
            }
        },
        resolve: {
            // 將 `.ts` 新增為一個可解析的副檔名。
            extensions: ['.js','.vue','.ts','.json']
        },
        devServer: {
            port: 8080,
            hot: true,
            grogress: true,
            historyApiFallback: true
        }   
}

src/index.js

import Vue from 'vue'
import app from './router.vue'
Vue.config.productionTip = false
new Vue({
  el: '#app', 
  render: function (h) {
    return h(app)
  }
});

相關文章