webpack 从零开始(下

本文深入探讨了webpack的HMR模块热替换,介绍了如何关闭和解决相关问题。接着讲解了生产环境的配置,利用webpack-merge工具进行配置合并。还涉及了懒加载的应用,并展示了如何配置Vue开发环境,包括处理静态资源和解决跨域问题。

webpack 从零开始(下

简介: 本文主要讲述 HMR (模块热替换)、懒加载,还有搭建vue 开发环境
上文: webpck从零开始(中

八 、HMR模块热替换

使用HMR 提高生产效率 从 webpack-dev-server v4.0.0 开始,热模块替换是默认开启的。
检查一下 俺们的版本是 4.110,那就关了试试
修改devServer:

devServer: {
	...
	hot: true
}

npm run serve
修改 index.css

div{
	..
	width: 200px;
	height: 200px;
}

发生了编译 浏览器刷新了。。。删掉

div{
	...
}

出了一个bug,css样式不能加载

Refused to apply style from 'http://localhost:8080/index.30f269.css?1663006881954' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

关了热替换

hot: false

好像没事了 哈哈哈。。。检查了一下 link 加载路径 多了 localhost:8080
暂时没找到bug的原因 先这样吧

九、生产环境

在生产环境和开发环境,不同的构建目标存在巨大差异,由于要遵循逻辑分离,我们通常建议为每个环境编写彼此独立的 webpack 配置。
webpack-merge
使用此工具合并“common” 配置

cnpm install --save-dev webpack-merge

修改文件

新建 webpack.dev.js
        webpack.prod.js
        webpack.common.js

从原配置文件粘贴代码到webpack.common.js并进行修改

const path = require('path')
const { VueLoaderPlugin } = require('vue-loader')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
 entry: {
   index: './src/index.js',
   another: './src/another.js'
 },
 output: {
   filename: "[name].[contenthash:6].js",
   path: path.resolve(__dirname,'dist'), //__dirname 指向项目根目录
   clean: true,
 },
 module: {
  rules: [
    {
      test: /\.css$/i,
      use: [MiniCssExtractPlugin.loader,'css-loader']
    },
    {
      test: /\.scss$/i,
      use: [MiniCssExtractPlugin.loader,'css-loader','sass-loader']
    },
    {
      test: /\.vue$/i,
      use: ['vue-loader']
    }
  ]
 },
 plugins: [
   new VueLoaderPlugin(),
   new HtmlWebpackPlugin({
     title: 'Webpack Begin'
   }),
   new MiniCssExtractPlugin({
     filename: "[name].[contenthash:6].css"
   })

 ],
 optimization: {
   runtimeChunk: 'single',
   splitChunks: {
     cacheGroups:{
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: "all"
        }
       
     }
   }
 } 
 
}

粘贴代码到 webpack.dev.js

const { merge } = require('webpack-merge')
const common = require('./webpack.common.js') 

module.exports = merge(common,{
  mode: 'development',
  devtool: 'inline-source-map',
  devServer: {
    static: './dist',
    port: 8080,
    hot: false
  }
})

粘贴到 webpack.prod.js

const { merge } = require('webpack-merge')
const common = require('./webpack.common.js')

module.exports = merge(common,{
  mode: 'production'
})

修改 scripts

"serve": "webpack serve --open --config webpack.dev.js"
"build": "webpack --config webpack.prod.js"

测试一下 OK

十、懒加载

因为lodash这个库比较大,所以我们可以用懒加载的方式来引入,
即点击button以后才加载,
在index页面添加一个button

const el = document.createElement('div')
  const brEl = document.createElement('br')
  const buttonEl = document.createElement('button')

  el.innerHTML = 'Hello world!'
  buttonEl.innerHTML = "Click me and see the console"

  document.body.appendChild(el)
  document.body.appendChild(brEl)
  document.body.appendChild(buttonEl)
  
  buttonEl.onclick =e => import('./print') //主意onclick 大小写
  .then(module=>{
    const print = module.default
    print();
  }) 

十一、配置 vue开发环境

之前我们已经安装了 vue,因为使用了 html-webpack-plugin 生成html文件,
我们需要修改配置使用我们自定义的模板,方便挂载 app,新建public问件夹 copy
一份index.html

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

修改index.js

import App from './App.vue'
import { createApp } from 'vue'
import _ from 'lodash'
import './index.css'
import './index.scss'

createApp(App)
.mount("#app")

webpack.common.js修改html-webpack-plugin 配置

new HtmlWebpackPlugin({
	tempalte: './public/index.html'",
	filename: 'index.html '
})

template 写错啦 。。粗心

报错了
ReferenceError: BASE_URL is not defined
修改icon 路径,可以看hello world 了

<link rel="icon" href="<%=htmlWebpackPlugin.options.url %>/favicon.ico">

修改hello world 组件

<template>
  <div>
    <div class="main-container">
      <div>Welcome {{name}}</div>
      <ul class="list">
        <li v-for="i in 5" :key="i">{{i}}</li>
      </ul>
      <img class="girl-image" src="../assets/imgs/girl.jpeg" alt="美女图片">
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return {
      name: 'John'

    }
  }

}
</script>

<style lang="scss" scoped> 
.main-container{
  .girl-image{
   width: 200px;
    height: 200px;
    border-radius: 10px;
  }
}



</style>

添加rules 处理静态文件(图片

{
      test: /\.(png|jpe?g|gif|webp|ico)$/,
        type: 'asset',
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 小于10kb的图片会被base64处理
          },
        },
        // 配置资源输出位置和名称
        generator: {
          // 将图片文件输出到 imgs 目录中
          // 将图片文件命名 [name][hash:6][ext][query]
          // [name]: 之前的文件名称
          // [hash:6]: hash值取6位
          // [ext]: 使用之前的文件扩展名
          // [query]: 添加之前的query参数
          filename: 'imgs/[name][hash:6][ext][query]',
        },
        
    }

还需要:
使用bebel-loader 转译es6 代码
添加devServer proxy 请求代理解决跨域问题
安装其他插件等 这里不细述了
参考地址:
https://blog.youkuaiyun.com/qq_41867900/article/details/126408709

–本文完 感谢观看 错误是在所难免,请多谅解–

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值