Webpack-前端工程化的基石

2020-12-24  本文已影响0人  行走的蛋白质

在以前,为了减少 HTTP 请求,通常地,我们都会把所有的代码都打包成一个单独的 JS 文件。但是,如果这个 JS 文件体积很大的话,那就得不偿失了。

就拿咱们产品来说,都是 SPA 单页面应用,我们不可能在首屏加载所有的 JS 和 CSS 代码。

这时,我们不妨把所有代码分成一块一块,需要某块代码的时候再去加载它;还可以利用浏览器的缓存,下次用到它的话,直接从缓存中读取。很显然,这种做法可以加快我们网页的加载速度,webpack 刚好可以帮助我们。

1、什么是 webpack

webpack

2、为什么要使用 webpack

3、webpack 入门

 webpack-demo
 |- package.json
+ |- index.html
+ |- /src
+   |- index.js

4、配置 webpack.config.js

const path = require('path')
​
module.exports = {
 mode: 'development',
 entry: path.resolve(__dirname, 'src/index'),
 output: {
 filename: 'main.js',
 path: path.resolve(__dirname, 'bundle')
 }
}

5、plugins

const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
​
const HtmlPlugin = new HtmlWebpackPlugin({
 template: path.resolve(__dirname, 'index.html')
})
​
module.exports = {
 mode: 'development',
 entry: path.resolve(__dirname, 'src/index'),
 output: {
 filename: '[name].[chunkHash:8].js',
 path: path.resolve(__dirname, 'dist')
 },
 plugins: [
 new CleanWebpackPlugin(),
 HtmlPlugin
 ]
}

6、loader

const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
​
const HtmlPlugin = new HtmlWebpackPlugin({
 template: path.resolve(__dirname, 'index.html')
})
​
module.exports = {
 mode: 'development',
 entry: path.resolve(__dirname, 'src/index'),
 output: {
 filename: '[name].[chunkHash:8].js',
 path: path.resolve(__dirname, 'dist')
 },
 module:{
 rules: [{
 test: /\.js$/,
 use: ['babel-loader']
 }, {
 test: /\.css$/,
 use: ['style-loader', 'css-loader']
 }, {
 test: /\.less$/,
 use: ['style-loader', 'css-loader', 'less-loader']
 }]
 },
 plugins: [
 new CleanWebpackPlugin(),
 HtmlPlugin
 ]
}

7、webpack-dev-server

// package.json "start": "webpack-dev-server --inline --progress --color --open --port 8001"

8、 webpack 构建流程

9、优化 Webpack 的构建

10、vue-cli 脚手架简析

npm install @vue/cli
vue create myApp
上一篇 下一篇

猜你喜欢

热点阅读