工程化-webpack简单使用

核心概念

入口
module.exports = {
	entry: './path/to/my/entry/file.js'
};
输出
const path = require('path');

module.exports = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  }
}
Loader
const path = require('path');

module.exports = {
  output: {
    filename: 'my-first-webpack.bundle.js'
  },
  module: {
    rules: [
      {test: /\.txt$/, use: 'raw-loader'}
    ]
  }
}
插件
const HtmlWebpackPlugin = require('html-webpack-plugin') // 通过npm安装
const webpack = require('webpack') //用于访问内置插件

module.exports = {
  module: {
    rules: [
      {test: /\.txt$/, use: 'raw-loader'}
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({template: './src/index.html'})
  ]
}
模式/兼容性

webpack支持所有符合es5标准的浏览器,webpack的import()和require.ensure()需要Promise,如果你想支持旧版本浏览器,在使用这些表达式之前,还需要提前加载polyfill

npm install --save babel-polyfill

然后,使用import将其引入到我们的住bundle文件
src/index.js

import 'babel-polyfill';

搭建webpack

  1. 查看本地node和npm版本
  • node版本号10.16.0
  • npm版本号6.9.0
  • nvm安装指定版本的node
nvm install v10.16.0
nvm use 10.16.0
  1. 创建空文件夹并初始化项目,快速创建nodejs项目,生成package.json
npm init -y
  1. 安装webpack及依赖包webpack-cli
npm install webpack webpack-cli -D
  1. 配置package.json使用webpack
    这样就可以在命令行中使用npm run build执行webpack了
    (执行的时候会有报错请忽略,因为文件中只有package.json,还没有其他文件)
"scripts": {
   "build": "webpack"
 },

webpack配置

配置入口
  1. 创建webpack.config.js
const config = {
  entry: './src/index.js'
}

module.exports = config
  1. 创建src目录,并在里面创建index.js入口文件
  2. 执行npm run build构建index.js文件,默认构建到dist/main.js文件
配置输出
const path = require('path')

// 当前文件的绝对路径
// console.log(path.resolve())
// 当前文件的绝对路径拼接指定的路径
// console.log(path.join(__dirname, './dist'))
// filename: 打包后的文件名字
// path: 需要使用绝对路径

const config = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.join(__dirname, './dist')
  }
}

module.exports = config
loader的配置和使用
  1. 安装相关的loader依赖
    如css-loader、style-loader

npm install css-loader style-loader -D

  1. webpack.config.js中添加module
    注意use数组中的loader的顺序,它是倒叙执行的,先执行css-loader在执行style-loader,
    注意他俩的顺序不能颠倒,否则会报错
const path = require('path')

const config = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.join(__dirname, './dist')
  },
  module: {
    rules: [
      {test: /\.css$/, use: ['style-loader', 'css-loader']}
    ]
  }
}
module.exports = config
  1. 在src目录下创建index.css文件
body,html{
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  background: red;
}
  1. 在src下的index.js中引用
require('./index.css')
  1. 删除dist文件夹,执行npm run build重新构建
  2. 在dist文件夹中创建index.html,并引入bundle.js,验证是否将css文件构建成功
    在浏览器中打开index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  hello word
  <script src="bundle.js"></script>
</body>
</html>
  1. 配置sass-loader
  • 安装sass-loader

npm install sass-loader node-sass -D

  • 重新配置module
module: {
    rules: [
      {test: /\.(scss|css)$/, use: ['style-loader', 'css-loader', 'sass-loader']}
    ]
  }
  • 删除index.css创建inex.scss
body,html{
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  background: green;
}
  • 在index.js中引入index.scss
require('./index.scss')
  • 删除dist文件夹,重新构建并验证
配置插件(plugins)

插件用来解决loader无法实现的其他事

1. HtmlWebpackPlugin

该插件将为你生成一个 HTML5 文件

  • 执行下面的命令安装HtmlWebpackPlugin

npm install HtmlWebpackPlugin -D

  • 修改webpack.config.js
const path = require('path');
// 引入插件
const HtmlWebpackPlugin = require('html-webpack-plugin');

const config = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.join(__dirname, './dist')
  },
  module: {
    rules: [
      {test: /\.(scss|css)$/, use: ['style-loader', 'css-loader', 'sass-loader']}
    ]
  },
  // 添加插件
  plugins: [
    new HtmlWebpackPlugin({
      // 打包后创建的html文件的名字
      filename: 'index.html',
      // 模板html文件
      template: 'template.html'
    })
  ]
}

module.exports = config
  • 在根目录下创建template.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  hello word
</body>
</html>
  • 删除dist文件并重新打包构建
2. 热模块替换
  • 安装webpack-dev-server依赖

yarn add webpack-dev-server -D

  • 在package.js中进行配置
"scripts": {
    "build": "webpack",
    "watch": "webpack --watch",
    "hot": "webpack-dev-server"
 },
  • 在webpack.config.js中进行配置
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 新增加的
const webpack = require('webpack');

const config = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.join(__dirname, './dist')
  },
  module: {
    rules: [
      {test: /\.(scss|css)$/, use: ['style-loader', 'css-loader', 'sass-loader']}
    ]
  },
  // 新增加的
  devServer: {
    hot: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'template.html'
    }),
    // 新增加的
    new webpack.HotModuleReplacementPlugin()
  ]
}

module.exports = config
  • 执行npm run hot启动热更新
  • 启动后就可以通过localhost:8080访问到打包生成的html文件了,并且修改不用再手动进行构建
3. 配置babel
  1. 安装依赖

yarn add babel-loader @babel/core @babel/preset-env @babel/plugin-transform-runtime -D
yarn add @babel/runtime -S

  1. 跟目录下创建.babelrc文件
{
  "presets": [
    "@babel/preset-env"
  ],
  "plugins": [
    "@babel/plugin-transform-runtime"
  ]
}
  1. 在webpack.config.js文件中配置规则
module: {
  rules: [
    {test: /\.(scss|css)$/, use: ['style-loader', 'css-loader', 'sass-loader']},
    {test: /\.js/, loader: 'babel-loader'}
  ]
},
  1. 在src文件中创建一个js文件,里面使用es6的语法,并在index.js中使用import引用
4. clean-webpack-plugin
  1. 安装插件

yarn add clean-webpack-plugin -D

  1. webpack.config.js配置
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
plugins: [
  new HtmlWebpackPlugin({
     filename: 'index.html',
     template: 'template.html'
  }),
  new webpack.HotModuleReplacementPlugin(),
  new CleanWebpackPlugin()
]
5. copy-webpack-plugin

将单个文件或整个目录复制到构建目录

yarn add copy-webpack-plugin -D

const CopyWebpackPlugin = require('copy-webpack-plugin')
plugins: [
  new CopyWebpackPlugin([
  	// 将根目录下的assets文件夹拷贝到dist下文件名为assets
    {from: path.join(__dirname, 'assets'), to: 'assets'}
  ])
]
6. js,css,html等文件压缩

yarn add optimize-css-assets-webpack-plugin terser-webpack-plugin -D
如果需要用link来引用css文件的话还需要安装下面的插件
yarn add mini-css-extract-plugin -D

配置webpack.config.js

const TerserJSPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const config = {
	optimization: {
    	minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
  	},
  	module: {
	    rules: [
	      {test: /\.(scss|css)$/, use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']},
	      {test: /\.js/, loader: 'babel-loader'}
	    ]
	},
	plugins: [
		new MiniCssExtractPlugin({
			filename: '[name].css',
			chunkFilename: '[id].css',
		})
	]
}
模式mode
const config = {
	mode: 'development',
}
  • development 打包构建后的文件不进行压缩
  • production 打包构建后的文件进行了压缩
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值