动手写webpack配置 您所在的位置:网站首页 webpack文件hash 动手写webpack配置

动手写webpack配置

2024-07-14 15:29| 来源: 网络整理| 查看: 265

基于Webpack4.x + npm6.5 + node v10.10.0 +react+ vscode环境.

项目名webpackDemo;

上节:https://blog.csdn.net/fengsh998/article/details/88081807插件的引用。

本节主要说明下使用hash命名的好处,很多时候浏览器为我们访问页面的时候很多资源文件都都是缓存在本地。如果缓存时间没过期不会请求新的资源文件,但有时候如果对某个资源进行了修改,没及时更新就会有问题。因此webpack在打包的时候会为我们生成一个hash值。这个hash值会随源文件或资源的变动而变化,如果源文件不动,资源不动。啥也不动的情况下,多次编译生成的hash是一样。这个不用担心。并不会每次编译都产生不同的hash.

AdeMacBook-Pro-3:webpackdemo a$ npm run dev > [email protected] dev /Users/a/Documents/reactNative/reactstudy/webpackdemo > webpack-dev-server ℹ 「wds」: Project is running at http://localhost:8080/ ℹ 「wds」: webpack output is served from / ℹ 「wds」: Content not from webpack is served from /Users/a/Documents/reactNative/reactstudy/webpackdemo/dist ℹ 「wdm」: Hash: 3657098ad25ae41f7382 Version: webpack 4.29.6 Time: 1397ms ...

从上面中我们可以看到产生的hash 3657098ad25ae41f7382

怎么使用这个hash值呢。在webpack.config.js中在你需要使用hash值来命名输出的名件名时。通过[hash]来读取。

const path = require('path'); const htmlplugin = require('html-webpack-plugin') module.exports = { ... output: { filename: 'bundle.[hash].js', path: path.resolve(__dirname, 'dist') }, ... }

这样修改之后,就会带hash值了。

但加了hash值之后。每次改动源码编译后都会产生新的hash文件,那第dist里就会有好多没有用的过时的文件垃圾。每次都手动删除。比较烦。这时可以按装一个clean-webpack-plugin  https://www.npmjs.com/package/clean-webpack-plugin 

const path = require('path'); const htmlplugin = require('html-webpack-plugin') const CleanWebpackPlugin = require('clean-webpack-plugin') let pathsToClean = [ 'dist/*.*', 'build' ] let cleanOptions = { root: __dirname, verbose: true, dry: false } module.exports = { ... output: { filename: 'bundle.[hash].js', path: path.resolve(__dirname, 'dist') }, plugins: [ new CleanWebpackPlugin(pathsToClean, cleanOptions), new htmlplugin({ title: 'Html 插件 Demo', template: path.join(__dirname, 'public', 'index.html') }) ], ... }

到此hash算是完成了基本使用吧。

 

 

 

 

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有