最近在看webpack4,深感知识浅薄,这两天也一直在思考cli的配置,借助一些别人的实践,尝试本身搭建vue的项目,这里使用webpack4版本,以前我在网上查找别人的vue项目搭建,可是都是webpack3的,因此写了本文,若是有错误,或者有什么问题,请大佬们指出javascript
关于webpack的本文不会多说,请看webpack文档css
关于本文的github地址vue-MYCLIhtml
完成了基本的js vue css 的配置 基础版本vue
安装了vue-router vuex less eslint,webpack配置已经调整完毕,基本可使用 完整版本java
npm init
安装webpack4node
npm install webpack webpack-cli --save-dev
在开始以前先实验一下环境react
根目录新建文件 index.htmlwebpack
<!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>Vue</title> </head> <body> <script src="./src/mian.js"></script> </body> </html>
根目录新建文件 src/main.jsgit
console.log("我是main");
根目录新建文件webpack.config.jses6
const path = require('path') module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, dist), filename: 'index.js' } }
打包js文件
npx webpack --config webpack.config.js
会看到一些报错,只要构建成功就ok
这里说明环境是没有问题的
开始安装vue-loader吧
npm i webpack vue vue-loader -D //-D就是--save-dev
安装完成后看输出
提示安装的依赖要安装
npm install webpack css-loader -D
安装完毕后新建src/app.vue
<template> <div> 你好 {{ data }} </div> </template> <script> export default { data(){ return { data: "Vue" } } } </script> <style scoped> </style>
.vue文件是没法直接运行的,须要在webpack里面配置loader
这里参照某课的老师的方法,html用webpack生成(后面说明)
在根目录新建index.js 删除index.html
import Vue from 'vue' import App from './app.vue' const root = document.createElement('div') document.body.appendChild(root) new Vue({ render: (h) => h(App) }).$mount(root)
改写webpack.config.js
const path = require('path') module.exports = { entry: path.resolve(__dirname, 'src/index.js'), //关于path模块能够看看阮一峰的教程 http://javascript.ruanyifeng.com/nodejs/path.html#toc0 output: { path: path.resolve(__dirname, 'dist'), filename: 'index.js' }, module: { rules: [{ test: /\.vue$/, loader: 'vue-loader' }] } }
在package里面添加脚本
"build": "webpack --config webpack.config.js"
控制台运行
npm run build
不出意外会报错
这里有2个问题,一个是没有指定mode 一个是没有引用vue的插件
咱们须要改写webpack.config.js,在config里面加一行
mode: 'production', //暂时指定为生产环境
再次运行npm run build
会报错,须要安装一个包
这个报错,本来在vue-loader就有提示,不知道为何如今没有,运行以前报错
Error: [vue-loader] vue-template-compiler must be installed as a peer dependency, or a compatible compiler implementation must be passed via options
安装vue-template-compiler
npm install vue-template-compiler -D
再再次运行npm run build
假如按步骤来不除意外这里能够打包成功了~~~~
咱们须要验证打包文件时候是否正确,因此这里使用插件HtmlWebpackPlugin,帮咱们自动建立html文件,而且在后续的hash文件名上颇有用,具体能够看官方介绍
npm install html-webpack-plugin -D
改webpack.config.js代码
const path = require('path') const { VueLoaderPlugin } = require('vue-loader') var HtmlWebpackPlugin = require('html-webpack-plugin'); //引入插件 module.exports = { mode: 'production', //暂时指定为生产环境 entry: path.resolve(__dirname, 'src/index.js'), //关于path模块能够看看阮一峰的教程 http://javascript.ruanyifeng.com/nodejs/path.html#toc0 output: { path: path.resolve(__dirname, 'dist'), filename: 'index.js' }, module: { rules: [{ test: /\.vue$/, loader: 'vue-loader' }] }, plugins: [ new VueLoaderPlugin(), new HtmlWebpackPlugin() ] }
npm run build
打包一下,dist文件夹下面会有两个文件
打包Vue程序完成~~~~
至此完成了最基本的webpack配置
接下来咱们要完成的的配置开发环境
关于开发环境以及生成环境,webpack是须要区分的,根据文档模块,我决定在命令里面指定模式,相应的就将开发环境以及生成环境分开,
这里我使用的是提起基本的webpack配置使用webpack-merge
这个包来拼接咱们webpack配置
npm i webpack-merge -D
修改配置文件
将各各环境的代码区分开,webpack的结构是这样的
webpack.config.base.js
const path = require('path') const config = { entry: path.resolve(__dirname, '../src/index.js'), output: { path: path.resolve(__dirname, 'dist'), filename: 'index.js' }, module: { rules: [{ test: /\.vue$/, loader: 'vue-loader' }] } } module.exports = config
webpack.config.build.js
const { VueLoaderPlugin } = require('vue-loader') const HtmlWebpackPlugin = require('html-webpack-plugin') const merge = require('webpack-merge') const baseConfig = require('./webpack.config.base') const config = merge(baseConfig ,{ plugins: [ new VueLoaderPlugin(), new HtmlWebpackPlugin() ] }) module.exports = config
这里配置开发环境就是重头戏了,咱们使用webpack-dev-server
webpack-dev-server是一个小型的Node.js Express
服务器,代码都跑在内存里面
安装webpack-dev-server
npm install webpack-dev-server -D
webpack.config.dev.js
const webpack = require('webpack') const merge = require('webpack-merge') const baseConfig = require('./webpack.config.base') const { VueLoaderPlugin } = require('vue-loader') const HtmlWebpackPlugin = require('html-webpack-plugin') const config = merge(baseConfig, { devServer: { port: '8000', host: 'localhost', hot: true, //热加载 //quiet: true //控制台中不输出打包的信息 }, plugins: [ new VueLoaderPlugin(), new HtmlWebpackPlugin(), new webpack.HotModuleReplacementPlugin() ] }) module.exports = config
最后在package里面添加脚本
"build": "webpack --mode=production --config build/webpack.config.build.js", "dev": "webpack-dev-server --mode=development --progress --config build/webpack.config.dev.js"
执行npm run dev
查看控制台
这就成功了,在浏览器里面输入http://localhost:8000/,修改app.vue文件,实现了vue-cli的热加载了~~~~
接下来完善一下,不能只有.vue文件的loader,其余的webpack也要认识
咱们配置一下图片的loader,以及css的loader,同时css使用postcss进行预处理
url-loader 用于将文件转换为base64 URI file-loader是依赖loader
npm i url-loader file-loader -D
添加配置webpack.config.base.js>module>rules
{ test: /\.(gif|png|jpg|svg)$/, use: [{ loader: 'url-loader', options: { limit: 2048, name: 'resources/[path][name].[hash:8].[ext]' } }] },
配置css(vue-cli里面的实现很是友好,有机会能够去看看) 下面的是最简单的配置
npm install css-loader -D npm install vue-style-loader -D npm install postcss-loader -D
添加配置webpack.config.base.js>module>rules (postcss不了解谷歌一下)
{ test: /\.css$/, use: [ 'vue-style-loader', 'css-loader', { loader: 'postcss-loader', options: { sourceMap: true //启用源映射支持,postcss-loader将使用其余加载器给出的先前源映射并相应地更新它 } } ] }
npm install autoprefixer -D
根目录新建文件postcss.config.js,安装autoprefixer (自动添加浏览器前缀)
const autoprofixer = require('autoprefixer') module.exports = { plugins: [ autoprofixer() ] }
配置到这里基本的图片以及css就配置完成了,运行一下试试 npm run dev
我找src下面建立了assets/img/user.jpg
app.vue
<template> <div> 你好 {{ data }} <img src="./assets/img/user.jpg"> </div> </template> <script> export default { data(){ return { data: "Vue Cli" } } } </script> <style> div{ font-size: 20px; color: red; } img { width: 100px; } </style>
实现了开发环境的图片以及css的配置
打包一下试试
build后生成的目录是这样的
这不是咱们想要的,webpack把代码,类库,css都打包在一块儿,这样不论是上线仍是首屏加载都有影响,因此这里咱们要优化webpack
在处理以前想安装一个能够帮助咱们每次build以前自动删除上次build生成的文件的插件
clean-webpack-plugin
这个插件不知道为何,怎么配置路径都没效果
这里我使用rimraf来进行删除(vue-cli也是使用rimraf,可是他是写在代码里面)
npm install rimraf -D
在package里面变一下脚本,让打包以前帮咱们删除以前到打包文件
"build-webpack": "webpack --mode=production --config build/webpack.config.build.js", "delete": "rimraf dist", "build": "npm run delete && npm run build-webpack"
它会将全部的入口 chunk(entry chunks)中引用的
*.css
,移动到独立分离的 CSS 文件
npm install extract-text-webpack-plugin@next -D
由于开发环境和生产环境不同
咱们须要将css部分的代码分环境配置
module: { rules: [{ test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "vue-style-loader", use: [ 'css-loader', { loader: 'postcss-loader', options: { sourceMap: true } } ] }) }] },
这样的话,咱们开发环境不影响依旧是以前到模式,build的时候用ExtractTextPlugin帮咱们分离非js文件,实现css的分离打包
咱们打包一下试试npm run build
接下来是分离js文件,就是将库文件以及咱们的代码分离开,利于上线后的浏览器缓存,代码会常常变,库不会常常变
在webpack4以前js分离用的插件是CommonsChunkPlugin,不过这插件如今移除了,如今用的是optimization.splitChunks 来进行公共代码与第三方代码的提取,splitChunks参数以下
optimization: { splitChunks: { chunks: "initial", // 代码块类型 必须三选一: "initial"(初始化) | "all"(默认就是all) | "async"(动态加载) minSize: 0, // 最小尺寸,默认0 minChunks: 1, // 最小 chunk ,默认1 maxAsyncRequests: 1, // 最大异步请求数, 默认1 maxInitialRequests: 1, // 最大初始化请求书,默认1 name: () => {}, // 名称,此选项课接收 function cacheGroups: { // 缓存组会继承splitChunks的配置,可是test、priorty和reuseExistingChunk只能用于配置缓存组。 priority: "0", // 缓存组优先级 false | object | vendor: { // key 为entry中定义的 入口名称 chunks: "initial", // 必须三选一: "initial"(初始化) | "all" | "async"(默认就是异步) test: /react|lodash/, // 正则规则验证,若是符合就提取 chunk name: "vendor", // 要缓存的 分隔出来的 chunk 名称 minSize: 0, minChunks: 1, enforce: true, reuseExistingChunk: true // 可设置是否重用已用chunk 再也不建立新的chunk } } } }
官方包括这解释,我并非很看懂,因此打包策略并非很好
在webpack.config.build.js>config
output: { filename: '[name].[chunkhash:8].js' }, optimization: { splitChunks: { chunks: "all", cacheGroups: { vendor: { test: /node_modules/, //这里虽然分离了,可是没有作到按需引入,看官方配置也不是很明白 name: 'vendors', chunks: 'all' } } }, runtimeChunk: true }
build一下查看目录,能够看出代码与库之间分离了
这里处理一下git 新建文件.gitignore
.DS_Store node_modules/ /dist/ npm-debug.log* yarn-debug.log* yarn-error.log* # Editor directories and files .idea .vscode *.suo *.ntvs* *.njsproj *.sln
处理一下编译器的统一配置
新建文件 .editorconfig,(关于editorconfig,以及配置解释)
root = true [*] charset = utf-8 indent_style = space indent_size = 2 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true
还有一点要注意,假如没有效果,vscode须要安装一个插件EditorConfig for VS Code
,其余编译器不太清楚
处理一下ES6,以及js文件的webpack的loader配置
今天装了babel-loader8.0.0 报错报一上午,心态都搞崩了,因此这里我使用的是7版本
npm install babel-loader@7 babel-core babel-preset-env -D
在webpack.config.base.js>module>rules里面添加代码
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }
新建文件 .babelrc
{ "presets": [ "env" ] }
首先检查开发环境
我新建了一个es6语法的js 导入到app.vue里面
运行结果
eslint的安装相对简单,能够看官方指南
npm install --save-dev eslint eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node
由于.vue文件不会是纯js代码,因此,咱们须要安装额外的解析的插件
npm install eslint-plugin-html -D
而后咱们配置eslint到咱们的项目
在根目录新建文件.eslintrc
{ "extends": "standard", "plugins": [ "html" ], "rules": { "no-new": "off" //由于new Vue可是eslint默认不准new 咱们须要把这个关掉 } }
在package里面添加两行脚本
"lint": "eslint --ext .js --ext .jsx --ext .vue src/", "lint-fix": "eslint --fix --ext .js --ext .jsx --ext .vue src/"
如今运行npm run lint
即检查项目
运行npm run lint-fix
,便是将不规范的地方修正
下一步咱们配置到咱们的webpack里面让运行的时候同时检查代码
npm install eslint-loader babel-eslint -D
改写配置文件
{ "extends": "standard", "plugins":[ "html" ], "parser":"babel-eslint", "rules": { "no-new": "off" } }
在webpack.config.base里面的module> rules 里面加一个字段
{ test: /\.(vue|js|jsx)$/, loader: 'eslint-loader', exclude:/node_modules/, enforce: 'pre' //预处理 }
至此,基本的vue项目骨架的搭建完毕了,后面还有vue-router 以及vuex less的安装,请查看个人github,固然他没有vue-cli那么强大,或许最大的益处是让咱们熟悉一个vue项目的大体webpack配置,固然咱们能够一步一步的优化项目