webpack搭建vue环境

1、创建项目地址

1
2
3
mkdir webpack-vue
cd webpack-vue
npm init // 初始化项目并创建package.json (确认数据不用修改时可以使用npm init -y直接创建)

2、安装 webpack,修改启动命令

 2.1、安装 webpack 环境

1
npm install webpack@5.68.0 webpack-cli@4.9.2 -D

 2.2、修改 package.json

1
2
3
4
5
// package.json
"scripts": {
"dev":"webpack ./src/main.js --mode development",
"build": "webpack --mode production"
},

3、开始配置常规功能

 3.1、新建一个 build 文件夹

1
2
mkdir build
echo null>build/webpack.config.js

 3.2、创建并修改 build/webpack.config.js 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//  build/webpack.config.js 配置
const path = require('path')
module.exports = {
mode: 'development',
entry: {
// 配置文件入口
main: path.resolve(__dirname, '../src/main.js'),
},
output: {
// 输出
// 配置打包文件输出目录
path: path.resolve(__dirname, '../dist'),
// 生成的 js 文件名称
filename: 'js/[name].[hash:8].js',
// 生成的 chunk 名称
chunkFilename: 'js/[name].[hash:8].js',
// 资源引用路径
publicPath: '/',
},
}

 3.3、修改启动命令

1
2
3
4
5
// package.json
"scripts": {
"dev":"webpack ./src/main.js --config ./build/webpack.config.js",
"build": "webpack --mode production"
},

4、将 ES6+转化为 ES5

 4.1、将 ES6+ 转为 ES5 代码

1
2
3
npm install babel-loader@8.2.3
@babel/core@7.17.2
@babel/preset-env@7.16.11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// build/webpack.config.js
module.exports = {
...
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
},
],
},
],
},
}

 4.2、创建 babel.config.js 文件,并修改内容

1
2
3
4
5
6
7
8
9
10
11
12
13
echo null>babel.config.js; // 创建文件

// babel.config.js
module.exports = {
presets: [
[
"@babel/preset-env",
{
useBuiltIns: "usage"
}
]
],
}

 4.3、将 ES6+ API 转 ES5

babel-loader 只会将 ES6/7/8 语法转换为 ES5 语法,但是对新 api 并不会转换。

1
npm install @babel/polyfill@7.12.1
1
2
3
4
5
// build/webpack.config.js
entry: {
// 配置文件入口
main: ['@babel/polyfill', path.resolve(__dirname, '../src/main.js')],
},

5、配置 scss 转 css

sass-loader, dart-sass 主要是将 scss/sass 语法转为 css
css-loader 主要是解析 css 文件
style-loader 主要是将 css 解析到 html 页面 的 style 上

 5.1、安装 sass 环境

1
npm install sass-loader@12.5.0 dart-sass@1.25.0 css-loader@6.6.0 style-loader@3.3.1 -D

 5.2、修改 webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// build/webpack.config.js
module: [
...
{
test: /\.(scss|sass)$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
importLoaders: 2
}
},
{
loader: 'sass-loader',
options: {
implementation: require('dart-sass')
}
}
]
},
]

6、配置 postcss 实现自动添加 css3 前缀

 6.1、安装 css3 环境

1
npm install postcss-loader@6.2.1 autoprefixer@10.4.2 -D

 6.2、修改 webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// build/webpack.config.js
{
test: /\.(scss|sass)$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
importLoaders: 2
}
},
{
loader: 'sass-loader',
options: {
implementation: require('dart-sass')
}
},
+ {
+ loader: 'postcss-loader'
+ }
]
},

 6.3、创建 postcss.config.js 文件

1
2
3
4
5
6
7
8
echo null>postcss.config.js

// postcss.config.js
module.exports = {
plugins: {
autoprefixer: {}
}
}

7、使用 html-webpack-plugin 来创建 html 页面

 7.1、安装 html-webpack-plugin

1
npm install html-webpack-plugin@5.5.0 -D

 7.2 新建 public/index.html 页面

1
2
mkdir public
echo null>public/index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

 7.3、修改 webpack.config.js

1
2
3
4
5
6
7
8
9
10
// build/webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
...
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '../public/index.html')
}),
]
}

8、配置热更新功能( devServer)

 8.1、安装 webpack-dev-server

1
2
3
4
5
6
7
8
9
10
11
12
npm install webpack-dev-server@4.7.4 -D

// build/webpack.config.js

devServer: {
static: path.join(__dirname, 'dist'), // 服务器资源的根目录
hot: true, //启用热加载
host: 'localhost',
port: 9000, //端口号
open: true, // 服务器启动后打开默认浏览器
},
module:{...}

9、配置 webpack 打包 图片、媒体、字体等文件

 9.1、安装 file-loader、url-loader 环境

1
npm install file-loader@6.2.0 url-loader@4.1.1 -D

 9.2、修改 build/webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// build/webpack.config.js

module: {
rules: [
...
{
test: /\.(jpe?g|png|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 4096,
fallback: {
loader: 'file-loader',
options: {
name: 'img/[name].[hash:8].[ext]'
}
}
}
}
]
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
use: [
{
loader: 'url-loader',
options: {
limit: 4096,
fallback: {
loader: 'file-loader',
options: {
name: 'media/[name].[hash:8].[ext]'
}
}
}
}
]
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 4096,
fallback: {
loader: 'file-loader',
options: {
name: 'fonts/[name].[hash:8].[ext]'
}
}
}
}
]
},
]
}

10、定义环境变量

1
npm i cross-env@7.0.3 webpack-merge@5.8.0 mini-css-extract-plugin@2.5.3 -D

 10.1、在 build 下创建 webpack.dev.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// build/webpack.dev.js

const path = require('path');

module.exports = {
devServer: {
static: path.join(__dirname, 'dist'),
hot: true, //启用热加载
host: 'localhost',
port: 9000, //端口号
open: true, // 服务器启动后打开默认浏览器
historyApiFallback: true, // 解决history模式刷新404
},
}

 10.2、在 build 下创建 webpack.prod.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// build/webpack.prod.js

const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
// 出口
output: {
filename: 'js/[name]-[chunkhash].js',
path: path.resolve(__dirname, '../dist')
},
plugins: [
new MiniCssExtractPlugin({
filename: "css/[name].css",
chunkFilename: "css/[name].css"
})
]
}

 10.3、修改 webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
// build/webpack.config.js

const devConfig = require('./webpack.dev.js');
const prodConfig = require('./webpack.production.js');
const {merge} = require('webpack-merge');
const isProduct = process.env.NODE_ENV === 'production';

- module.exports = {
+ const config = {

+ module.exports = isProduct ? merge(config, prodConfig) : merge(config, devConfig);

 10.4、修改 package.json

1
2
3
4
"scripts": {
"serve": "cross-env NODE_ENV=development webpack-dev-server --config ./build/webpack.config.js",
"build": "cross-env NODE_ENV=production webpack --config ./build/webpack.config.js"
},

以上就是 webpack 的简单使用,如果只是简单的 html 开发,但这儿就应该够用了

11、集成 vue3 到项目中

 11.1 安装 vue3 及其环境

1
2
3
npm install vue@next // 安装最新版vue3
npm i -D vue-loader@next @vue/compiler-sfc // 让webpack支持vue语法和单文件组件(sfc)
npm i vue-template-compiler@2.6.14 // 编译模板

 11.2、在 src 下创建 App.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
<div class="App">
Hello World
</div>
</template>

<script>
export default {
name: "App",

data() {
return {};
},
};
</script>

<style lang="sass" scoped>
.App {
color: skyblue;
}
</style>

 11.3、修改 build/webpack.config.js

1
2
3
4
5
6
7
8
// build/webpack.config.js

const { VueLoaderPlugin } = require('vue-loader'); // 引入VueLoaderPlugin

plugins: [
...
new VueLoaderPlugin(), // 新增 VueLoaderPlugin
],

 11.4、修改 src/main.js

1
2
3
4
5
6
7
// src/main.js

import {createApp} from 'vue'

import App from './App.vue'

createApp(App).mount('#app')

12、将 vue-router 集成到项目中

 12.1、安装 vue-router

1
npm install vue-router@4 // vue3.X 对应使用的vue-router@4.X

 12.2、创建 src/route/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/route/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'

const router = createRouter({
history: createWebHistory(), // history 模式
routes: [
{
path: '/',
redirect: '/Home',
},
{
name: 'Home',
path: '/Home',
component: Home,
},
{
name: 'About',
path: '/About',
component: () => import('../views/About.vue'),
},
],
})
export default router

 12.3、在 src 中创建 views/Home.vue

1
2
3
4
5
// src/views/Home.vue
<template>
<h1>this is page Home</h1>
<a @click="$router.push('/About')">跳转去About</a>
</template>

 12.4、在 src 中创建 views/About.vue

1
2
3
4
5
// views/About.vue
<template>
<h1>this is page About</h1>
<a @click="$router.push('/Home')">跳转去Home</a>
</template>

 12.5、修改 main.js 和 App.vue

1
2
3
// src/main.js
import router from './route'
createApp(App).use(router).mount('#app');
1
2
3
4
5
6
7
8
9
10
// src/App.vue
<template>
<router-view></router-view>
</template>

<script>
export default {
name: "App",
};
</script>

13、将 vueX 集成到项目中

 13.1、安装 vuex

1
npm install -save vuex@4  // vue3.X 对应的vuex@4.X

 13.2、在 src 目录下创建 store/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/store/index.js

import { createStore } from 'vuex'

export default createStore({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
},
modules: {
}
})

 13.3、修改 src/main.js

1
2
3
4
// src/main.js

+ import store from './store'
createApp(App).use(router).use(store).mount('#app');

 13.4、修改 src/views/Home

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<h1>this is page Home---{{ count }}</h1>
<button @click="$store.commit('increment')">我要加</button>
<a @click="$router.push('/About')">跳转去About</a>
</template>

<script>
export default {
computed: {
count() {
return this.$store.state.count;
},
},
};
</script>

 13.5、修改 src/views/About.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/views/About.vue

<template>
<h1>this is page About---{{ count }}</h1>
<button @click="$store.commit('increment')">我要加</button>
<a @click="$router.push('/Home')">跳转去Home</a>
</template>

<script>
export default {
computed: {
count() {
return this.$store.state.count;
},
},
};
</script>

项目地址: http://git.tiandingyu.cn/wxj/webpack-vue3