1、webpack 的安装
npm init -y
yarn add webpack webpack-cli --dev //安装webpack
2、webpack 的作用
- 转译代码(ES6 转为 ES5 ,SCSS 转为 CSS)
- 构建 build
- 代码压缩
- 代码分析
3、webpack 转译 JS
var path = require('path');
module.exports = {
mode: 'development',//development 用于开发者模式,production 用于用户使用
entry: './foo.js', //入口文件,如.src/index.html
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'foo.bundle.js' //出口,在 dist 文件夹中
//使用 'index.[contenthash].js'可以利用哈希做好HTTP缓存
}
};
rm-rf dist ; npx webpack
//删除 dist 文件,重新生成 webpack
//如果使用不了就用绝对路径:./node_modules/.bin/webpack
"scripts":{
"build":"rm -rf dist && webpack"
}
4、webpack 转译 HTML
yarn add html-webpack-plugin --dev
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
module.exports = {
entry: 'index.js',
output: {
plugins: [new HtmlWebpackPlugin(
{
title: '网页 title',
template: 'src/assets/test.html'//使用该模板生成 html
}
)]
};
- 使用
<%= htmlWebpackPlugin.options.title %>来使用模板中的 title
5、webpack 转译 CSS
yarn add css-loader --dev
yarn add style-loader --dev
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
};
- 该方法会在 CSS 文件的内容放到 html文件中的 的 style 标签中
6、用 webpack 把 CSS 抽成文件
yarn add mini-css-extract-plugin --dev
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
chunkFilename: '[id].[contenthash].css',
}),
],
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '/public/path/to/',
},
},
'css-loader',
],
},
],
},
};
- 最后会在 html 文件中 使用 link 引入 CSS 文件
7、使用 webpack 转译 scss
yarn add sass-loader dart-sass --dev
module.exports = {
module: {
rules: [
{
test: /\.scss$/i,
use:
'style-loader',
'css-loader',
{
loader:'sass-loader',
options:{
implementation:require('sass')
}
},
],
},
],
},
};
8、使用 webpack 转译 scss
yarn add less --dev
yarn add less-loader --dev
module.exports = {
module: {
rules: [
{
test: /\.less$/,
loader:['style-loader','css-loader','less-loader',
},
],
},
};
9、使用 webpack 加载图片
yarn add file-loader --dev
rules: [
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
],
},
],
10、使用 webpack dev server
- 首先确保 mode: 'development'
- 在 webpack.config.js 文件中添加
module.exports = {
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
},
};
yarn add webpack-dev-server --dev
"scripts": {
"start": "webpack-dev-server --open",
},
- 使用
yarn start 运行webpack-dev-server