webpack-02:前端开发环境搭建-02

185 阅读2分钟

1、图片

file-loader url-loader

url-loader 内部 依赖了 file-loader

npm install file-loader
      // file-loader 处理图片
      {
        test: /\.(png|jpe?g|gif|webp)$/,
        use: {
          loader: 'file-loader', // 或者用 url-loader (file-loader 加强版内部依赖 file-loader)
          options: {
            name: '[name].[hash].[ext]',
            outputPath: 'images', // 图片输出位置
            publicPath: '../images/', // 图片的引用位置, 图片的路径 + 图片的名称
            // limit: 1024 * 11, // 单位 kb 针对url-loader
          },
        },
      },

[ext] 占位符表示 图片后缀

使用方式

import pic from './img/1.jpg'

console.log(pic) // 输出来是url   images/1.53e7a457c334c930ff8ebf22ac397169.jpg

2、clean-webpack-plugin 清理 dist文件

如何使用

const { CleanWebpackPlugin } = require('clean-webpack-plugin')

// ....

  plugins: [
    //...
    new CleanWebpackPlugin(),
  ],

关于缓存

1、浏览器客户端第一次访问一个静态资源链接,客户端是有缓存文件的
2、要清空 Chrome 的缓存,请按以下步骤操作:

打开chrome浏览器,使用Ctrl+Shift+Delete快捷键,就会打开清理浏览数据页面,选择清理缓存选项, 然后单击“清除浏览数据”按键即可。

或者单击浏览器上的扳手-->选项-->高级选项-->隐私设置一栏中的清楚浏览数据 之后重复上面的步骤。

课外拓展:

www.cnblogs.com/lguow/p/106…

blog.csdn.net/wml00000/ar…

关于 hash (资源文件后面加上hash 是 指纹策略)

设置缓存

// server.js
const http = require('http')
const fs = require('fs')

http.createServer(function (request, response) {
  console.log('request come', request.url)

  if (request.url === '/') {
    const html = fs.readFileSync('test.html', 'utf8')
    response.writeHead(200, {
      'Content-Type': 'text/html'
    })
    response.end(html)
  }

  if (request.url === '/script.js') {
    response.writeHead(200, {
      'Content-Type': 'text/javascript',
      'Cache-Control': 'max-age=200' // 浏览器缓存时间
    })
    response.end('console.log("script loaded twice")')
  }
}).listen(8888)

no-cache

不从缓存读取

'Cache-Control': 'max-age=2000000, no-cache', // 通过 no-cache,即使没过期浏览器也要向服务器验证,不会从缓存读取。

no-store 设置 no-store,即使服务器下发了缓存相关头,浏览器也会忽略任何和缓存相关的信息,发送请求不会携带相关头,直接去请求最新的数据

3、 针对 指纹策略 理解

hash:

针对的入口的js 是整个运行环境

chunkhash:针对chunks

contenthash: 针对 单个文件内容

针对多页面应用

entry: { 
  index: './src/index.js',
  list: './src/list.js',
}
    // html 模板
    new HtmlWebpackPlugin({
      template: './index.html',
      filename: 'index.html',
      chunks:['index']
    }),
    new HtmlWebpackPlugin({
      template: './list.html',
      filename: 'list.html',
      chunks:['list']
    }),
    // 用占位符 会 以 HtmlWebpackPlugin_0/1.html 命名