[vue-cli]不用vue-cli,你自己有搭建过vue的开发环境吗?流程是什么?
基本概念
首先先了解先webpack的基本概念,webpack属于一个构建工具,主要有mode、entry、output、loader、plugin这几部分组成。
目标
本文会带你实现一个简易的vuecli
具备和官方几乎一样的功能
实现移动端适配
使用eslint进行语法检查
进行开发和生产环境区分
安装
首先先创建好以下目录
config是配置目录,src是vue的目录,其中src目录下的server.js、client.js、entry-server.js、router.js不需要,这些属于ssr的配置部分,不在本次范围内。
通过npm进行安装webpack
通过npm init创建好一个package.json
npm install webpack webpack-cli -D
yarn add webpack webpack-cli -D
复制代码编写基本配置
实现一个简单的打包
新建src/index.js, 作为我们的入口文件
console.log('hello world')
复制代码
const path = require('path')
module.exports = {
mode: 'development',
entry: {
main: 'src/index.js'
},
output: {
path: path.join(__dirname, '../dist'),
filename: '[name].[hash:8].js'
}
}
复制代码然后在package.json的scripts里面添加一条build命令
{
"name": "webpack",
"version": "1.0.0",
"description": "",
"main": "",
"dependencies": {
"vue": "^2.6.10"
},
"scripts": {
"build": "webpack --config config/webpack.base.config.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.34.0",
"webpack-cli": "^3.3.4"
}
}
复制代码然后就可以通过npm run build进行打包,一个最基础的配置就算完成了,当然这些还远远不够,距离要完成的部分还有很多。
配置开发环境
由于项目需要区分开发环境还是线上环境,我们需要一个环境变量去维护
const process = require('process')
const env = process.env.NODE_ENV
module.exports = env
复制代码配置热更新
npm install webpack-dev-server webpack-merge html-webpack-plugin friendly-errors-webpack-plugin -D
复制代码
const webpack = require('webpack')
const path = require('path')
const env = require('./env')
const webpackBaseConfig = require('./webpack.base.config')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const merge = require('webpack-merge')
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const devConfig = merge(webpackBaseConfig, {
devServer: {
contentBase: path.join(__dirname, 'src'),
host: 'localhost',
port: 8080,
hot: true,
compress: true,
noInfo: true,
overlay: {
warnings: true,
errors: true
},
clientLogLevel: 'none'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': JSON.stringify(env)
}),
new HtmlWebpackPlugin({
title: 'hello world',
filename: 'index.html',
template: './src/page/index.html',
inject: true
}),
new FriendlyErrorsWebpackPlugin({
compilationSuccessInfo: {
messages: ['项目成功启动,地址是localhost:8080']
}
})
]
})
module.exports = devConfig
复制代码
安装依赖
npm install cross-env -D
复制代码
添加命令,并修改package.json
"scripts": {
"serve": "cross-env NODE_ENV=development webpack-dev-server --open --progress --colors --config config/webpack.dev.config.js",
"build": "cross-env NODE_ENV=production webpack --config config/webpack.prod.config.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
复制代码然后运行npm run serve就可以看到如下效果,然后你就可以各种改了,不用自己手动刷新页面了
配置loader解析,并提取css
npm install css-loader style-loader postcss-loader url-loader babel-loader @babel/preset-env @babel/core sass-loader node-sass responsive-loader vue-loader eslint-loader mini-css-extract-plugin autoprefixer VueLoaderPlugin @moohng/postcss-px2vw -D
css-loader style-loader 用于处理css
postcss-loader 可以使用
autoprefixer 通过postcss给浏览器不支持的css加前缀
@moohng/postcss-px2vw 处理移动端适配,使用px转vw 不支持的转rem
sass-loader node-sass 处理sass scss文件,因为我用的是这个,less换成less-loader即可
vue-loader 处理vue文件
mini-css-extract-plugin 提取项目中的css到一个单独的文件
babel-loader @babel/preset-env @babel/core 处理js兼容
url-loader responsive-loader 处理图片,小于一定大小转成base64
eslint-loader eslint-config-standard eslint-plugin-vue 对js vue进行语法检查,采用eslint-config-standard规范,不想要的可以忽略
复制代码修改之前的配置,改为下面的样子
const path = require('path')
const env = require('./env')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
mode: env,
entry: {
main: './src/index.js'
},
output: {
path: path.join(__dirname, '../dist'),
publicPath: '/',
filename: '[name].[hash:8].js',
chunkFilename: '[name].[chunkhash].js'
},
module: {
rules: [
{
test: /\.css$/,
use: [{
loader: MiniCssExtractPlugin.loader
}, 'css-loader', 'postcss-loader']
},
{
test: /\.(sass|scss)/,
use: [{
loader: MiniCssExtractPlugin.loader
}, 'css-loader', 'postcss-loader', 'sass-loader']
},
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
fallback: 'responsive-loader',
limit: 4096,
quality: 50,
name: '[name].[hash:8].[ext]',
outputPath: 'assets'
}
}
]
},
{
test: /\.vue$/,
use: ['vue-loader']
},
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
},
{
enforce: 'pre',
test: /\.(js)$/,
loader: 'eslint-loader',
exclude: /node_modules/
}
]
},
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
'~': path.resolve(__dirname, 'src/assets')
},
enforceExtension: false,
extensions: ['.js', '.vue']
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: '[name].[contentHash:8].css'
})
]
}
复制代码新建babel.config.js、postcss.config.js、.eslintrc.js
module.exports = {
presets: [
[
'@babel/env'
]
],
plugins: ['@babel/plugin-syntax-dynamic-import']
}
module.exports = {
plugins: {
autoprefixer: {},
'@moohng/postcss-px2vw': {
viewportWidth: 750,
rootValue: 750,
unitPrecision: 6,
minPixelValue: 1
}
}
}
module.exports = {
root: true,
extends: 'standard',
env: {
es6: true,
node: true
},
plugins: ['vue']
}
复制代码新建router/router.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from '../views/home'
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Home
}
]
})
export default router
复制代码修改src/index.js
import Vue from 'vue'
import app from './App.vue'
import router from './router/router'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(app)
}).$mount('#app')
复制代码至此 webpack开发版、基础配置就已经完成,现在可以运行npm run serve进行修改了
编写生产环境配置
生产环境需要做的就是打包页面生成dist文件,并对页面进行优化分包
继续安装依赖
npm install clean-webpack-plugin terser-webpack-plugin optimize-css-assets-webpack-plugin progress-bar-webpack-plugin cssnano -D
复制代码const webpack = require('webpack')
const env = require('./env')
const merge = require('webpack-merge')
const webpackBaseConfig = require('./webpack.base.config')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const ProgressBarPlugin = require('progress-bar-webpack-plugin')
const OptimizationCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const prodConfig = merge(webpackBaseConfig, {
optimization: {
splitChunks: {
chunks: 'all',
minSize: 0,
maxSize: 0,
name: true,
cacheGroups: {
commons: {
name: 'commons',
chunks: 'all',
minChunks: 2
}
}
},
minimizer: [
new TerserPlugin({
sourceMap: env === 'development',
terserOptions: {
cache: true,
compress: {
drop_debugger: true,
drop_console: true
}
}
})
]
},
stats: {
modules: false,
source: false
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'hello world',
filename: 'index.html',
template: './src/page/index.html',
inject: true
}),
new webpack.DefinePlugin({
'process.env': JSON.stringify(env)
}),
new OptimizationCssAssetsPlugin({
assetNameRegExp: /\.css$/g,
cssProcessor: require('cssnano')
}),
new ProgressBarPlugin({
callback: function (res) {
console.log('打包完成')
}
})
]
})
module.exports = prodConfig
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)