1.创建package.json文件
npm init -y(y是yes的缩写,即npm后面需要手动配置的选项采用默认配置)
2.下载基本依赖
npm i webpack webpack-cli webpack-dev-server -D ( -D 等同于--save-dev,也保存在package.json文件中,是在devDependencies下)
webpack 是真正执行打包工作的程序
webpack-cli webpack
的命令行接口
webpack-dev-server 是在本地开发阶段,用来在本地起一个 server
npm i vue vue-loader vue-template-compiler @vue/compiler-sfc -D
npm install style-loader css-loader -D
npm install --save-dev @babel/core @babel/cli @babel/preset-env babel-loader
3.创建目录结构
main.js
import { createApp } from "vue";
import App from './App.vue';
// import router from './router/index.js';
const app = createApp(App);
// app.use(router);
app.mount('#app');
app.vue
<template>
<div class="page">
<router-view></router-view>
</div>
</template>
<style lang="stylus">
#app
font-family Avenir, Helvetica, Arial, sans-serif
-webkit-font-smoothing antialiased
-moz-osx-font-smoothing grayscale
text-align center
color #2c3e50
margin-top 60px
</style>
4.webpack.config.js文件
// path 模块是 Node.js 官方提供的、用来处理路径的模块。
const path = require('path');
const { resolve } = path;
const { VueLoaderPlugin } = require('vue-loader')
const HtmlWebpackPlugin = require('html-webpack-plugin');
config = {
mode: 'production',
entry: {
main: './src/main.js'
},
module: {
rules: [
// 处理vue文件
{
test: /\.vue$/,
use: 'vue-loader'
},
{
test: /.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.js$/,
use: ['babel-loader'],
exclude: /node_modules/
}
]
},
output: {
// filename: 'assets/js/[name].[contenthash:6].js',
// path: resolve(__dirname, './dist'),
path: resolve(__dirname, 'dist'), // 打包后的文件输出的目录
filename: `js/[name]_[chunkhash:8].js`, // 设置打包后的 js 文件名,如果在文件名前增加文件路径,会将打包后的 js 文件放在指定的文件夹下
// filename: 'css/[name].[contenthash:6].css',
},
// 插件
plugins: [
new VueLoaderPlugin(), // vue单文件处理
new HtmlWebpackPlugin({
template: resolve(__dirname, './public/index.html'), // 为其指定一个路径。可以用于配置根据哪一个HTML文件来生成打包输出时的HTML文件。
filename: 'index.html', // 配置生成的HTML文件的文件名
chunks: ['main'],
inject: true,
title: '12254', // 配置项可以为插件生成的HTML页面配置标题内容
minify: {
html5: true,
collapseWhitespace: true,
preserveLineBreaks: false,
minifyCSS: true,
minifyJS: true,
removeComments: false
}
})
]
};
module.exports = config;
package.json
{
"name": "vue3-d1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack server --mode=development",
"build": "webpack --mode=production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/cli": "^7.23.9",
"@babel/core": "^7.24.0",
"@babel/preset-env": "^7.24.0",
"@vue/compiler-sfc": "^3.4.21",
"babel-loader": "^9.1.3",
"css-loader": "^6.10.0",
"html-webpack-plugin": "^5.6.0",
"style-loader": "^3.3.4",
"vue": "^3.4.21",
"vue-loader": "^17.3.1",
"vue-router": "^4.3.0",
"vue-template-compiler": "^2.7.16",
"webpack": "^5.90.3",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.0.3"
}
}
使用命令 npm run dev 就可以启动项目了