webpack demo

webpack

webpack-demo

1
2
3
4
yarn init
yarn add webpack webpack-cli --dev

npx webpack --version

在 package.json 中添加

1
2
3
4
"scripts": {
"build": "rm -rf dist && webpack",
"start": "webpack serve --open"
},

webpack-dev-server

1
yarn add webpack-dev-server --dev

在 webpage.config.js 中添加

1
2
3
4
devtool: 'inline-source-map',
devServer: {
static: './dist',
},

html-webpack-plugin

1
yarn add html-webpack-plugin --devex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
entry: 'index.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'index.[contenthash].js'
},
plugins: [new HtmlWebpackPlugin({
title: 'My App',
template: 'src/assets/index.html'
})],
};

css-loader

1
yarn add css-loader --dev
1
2
3
4
5
6
7
8
9
10
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
};

style-loader

1
yarn add style-loader --dev
1
2
3
4
5
6
7
8
9
10
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
};

mini-css-extract-plugin

1
yarn add mini-css-extract-plugin --dev
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
plugins: [new MiniCssExtractPlugin({
filename: '[name].[contenthash].css'
})],
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"],
}
]
}
};

sass-loader

1
yarn add sass dart-sass --dev
1
2
3
4
5
6
7
8
9
test: /\.scss$/i,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: { implementation: require("dart-sass") }
}
]

less-loader

1
yarn add less less-loader --dev
1
2
test: /\.less$/i,
use: ["style-loader", "css-loader", "less-loader"]

stylus-loader

1
yarn add stylus stylus-loader --dev
1
2
test: /\.styl$/i,
use: ["style-loader", "css-loader", "stylus-loader"]

file-loader

1
yarn add file-loader --dev
1
2
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]

path.resolve和__dirname