使用webpack配置一个小型vue-cli脚手架

monkeysuo 2019-11-04

简介

使用vue的朋友都是知道vue-cli,他是一个基于webpack的vue脚手架,通过vue-cli配置好一整套环境可以更快的开发,从而提高了工作效率。而我们可以学习它的一些配置可以熟悉webpack的构建流程,从而更好的开发,本文讲述了如何配置一个小型的vue-cli脚手架。

项目地址: mini-vue-cli

webpack开发环境基本配置

项目初始化

参考webpack文档

npm init
npm install webpack --save-dev
npm install --save-dev webpack-dev-server //开发环境webpack服务器
npm install --save-dev webpack-merge//合并配置参数时用到
npm install html-webpack-plugin --save-dev //输出文件自动写入html

webpack4+以上版本需要安排webpack-cli

npm install --save-dev webpack-cli
文件目录结构

使用webpack配置一个小型vue-cli脚手架

webpack.common.js

const path = require("path");
module.exports = {
    entry: './src/main.js',
    output: {
        filename: 'js/main.js',
        path: path.resolve(__dirname, 'dist')
    },
    plugins:[
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'index.html',
            inject: true
        }),
    ]
}

webpack.dev.js

const merge = require("webpack-merge");
const webpack = require("webpack");
const common = require('./webpack.common.js');
module.exports = merge(common, {
    devtool: 'inline-cheap-module-source-map', //详情https://www.webpackjs.com/configuration/devtool/
    devServer: {
        contentBase: 'index.html',
        hot: true,
        port: 8081
    },
    plugins: [
        //启用热更新配置项
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin(),
    ]
})

webpack.prod.js

const merge = require("webpack-merge");
const common = require('./webpack.common.js');
module.exports = merge(common, {
})

package.json

{
  "name": "mini-vue-cli",
  "version": "1.0.0",
  "description": "mini-vue-cli",
  "scripts": {
    "dev": "set NODE_ENV=development&&webpack-dev-server --inline --progress --config build/webpack.dev.js" //set NODE_ENV=development之后可以通过process.env.NODE_ENV来判断生产环境还是开发环境
    "build": "set NODE_ENV=production&&webpack --mode=production --config build/webpack.prod.js"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "webpack": "^4.39.3",
    "webpack-cli": "^3.3.7",
    "webpack-dev-server": "^3.8.0",
    "webpack-merge": "^4.2.2"
    }
}

此时,配置的webpack可以利用npm run dev进行启动webpack服务器和npm run build进行打包main.js文件中的引入的js资源

管理资源文件插件-loader

安装资源管理插件loader

上面的项目初始化只能对js进行编译打包,不能识别css、图片等资源,这时候需要进行安装loader插件进行资源管理。

安装css-loader file-loader url-loader sass-loader node-sass(sass-loader和node-sass配置sass环境,url-loader是基于file-loader,可以进行小图片转换base64)

npm install --save-dev style-loader css-loader file-loader sass-loader node-sass

postcss-loader autoprefixer两个插件可以自动为样式添加前缀,用于浏览器兼容

npm install postcss-loader autoprefixer --save-dev

打包时抽离文件中样式到一个文件中

npm install mini-css-extract-plugin  --save-dev //webpack4+版本使用,webpack4以下版本使用extract-text-webpack-plugin

打包前清除dist中的文件

npm install clean-webpack-plugin --save-dev

将一些不用打包的文件在打包后复制,如vue-cli中的static文件夹

npm install copy-webpack-plugin --save-dev
文件配置

webpack.prod.js

const merge = require("webpack-merge");
const {
    CleanWebpackPlugin
} = require('clean-webpack-plugin');
const common = require('./webpack.common.js');
module.exports = merge(common, {
    plugins: [
        new CleanWebpackPlugin(),
    ],
})

webpack.common.js

const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const devMode = process.env.NODE_ENV !== 'production';
module.exports = {
    entry: {
        app:'./src/main.js'
    },
    output: {
        filename: 'js/[name].js',
        path: path.resolve(__dirname, '../dist')
    },
    module: {
        rules: [{
                test: /\.(sa|sc|c)ss$/,
                use: [{
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            hmr: process.env.NODE_ENV === 'development',
                            reloadAll: true,
                        },
                    },
                    'css-loader',
                    'sass-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: [
                                require("autoprefixer")({
                                    'overrideBrowserslist': ['ie 9-11', 'last 5 version'] //兼容IE9到11,所有浏览器最近五个版本
                                })
                            ]
                        }
                    }

                ],
            },
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'index.html',
            inject: true
        }),
        new MiniCssExtractPlugin({
            filename: devMode ? 'css/[name].css' : 'css/[name].[hash].css',
            chunkFilename: devMode ? 'css/[id].css' : 'css/[id].[hash].css',
        }),
        new CopyWebpackPlugin([{
            from: path.resolve(__dirname, '../static'),
            to: path.resolve(__dirname, '../dist/static'),
            ignore: ['.*']
        }])
    ]
}

webpack中vue环境相关开发配置

安排编译vue的插件
npm install vue vue-router vue-style-loader vue-template-compiler --save-dev
webpack配置

webpack.common.js

const VueLoaderPlugin = require('vue-loader/lib/plugin');
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const devMode = process.env.NODE_ENV !== 'production';
module.exports = {
    entry: {
        app:'./src/main.js'
    },
    output: {
        filename: 'js/[name].js',
        path: path.resolve(__dirname, '../dist')
    },
    module: {
        rules: [
            {
                test: /\.(sa|sc|c)ss$/,
                use: [{
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            hmr: process.env.NODE_ENV === 'development',
                            reloadAll: true,
                        },
                    },
                    'css-loader',
                    'sass-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: [
                                require("autoprefixer")({
                                    'overrideBrowserslist': ['ie 9-11', 'last 5 version'] //兼容IE9到11,所有浏览器最近五个版本
                                })
                            ]
                        }
                    }
                ],
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader',
            },
        ]
    },
    plugins: [
        new VueLoaderPlugin(),
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'index.html',
            inject: true
        }),
        new MiniCssExtractPlugin({
            filename: devMode ? 'css/[name].css' : 'css/[name].[hash].css',
            chunkFilename: devMode ? 'css/[id].css' : 'css/[id].[hash].css',
        }),
        new CopyWebpackPlugin([{
            from: path.resolve(__dirname, '../static'),
            to: path.resolve(__dirname, '../dist/static'),
            ignore: ['.*']
        }])
    ]
}
vue相关文件配置

index.html

index.html文件中要写入一个id为app的div,不然启动报错Cannot find element: #app,参考

入口文件main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import './css/style.scss'
import './view/hello.vue'
new Vue({
    router,
    render: h => h(App)
}).$mount("#app")

路由文件router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import indexPage from '../view/hello.vue'
Vue.use(Router);
const router = new Router({
    routes: [{
        path: '/',
        component: indexPage,
    }]
})
export default router;
启动
npm run dev //浏览器中输入localhost:8081
打包
npm run build

打包优化

转换成es5语法
npm i babel-core babel-loader babel-preset-es2015 --save-dev //注意babel-loader和babel-core要对应,不然转不了
npm i babel-plugin-transform-runtime --save-dev
npm install --save-dev babel-polyfill
npm install --save-dev babel-preset-env
代码模块分割以及为打包后js添加添加chunkhash

分离模块参考分离每个模块,参考
https://segmentfault.com/a/1190000012828879?utm_source=tag-newest
https://webpack.docschina.org...
https://www.cnblogs.com/wmhua...
https://segmentfault.com/a/1190000014247030

webpack.prod.js

const merge = require("webpack-merge");
const path = require("path");
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const common = require('./webpack.common.js');
module.exports = merge(common, {
    output: {
        filename: 'js/[name].[chunkhash]js',
        path: path.resolve(__dirname, '../dist'),
    },
    optimization: {
        namedChunks: true,
        runtimeChunk: {
            name: 'manifest'
        },
        noEmitOnErrors: true, //编译错误时不生成
        splitChunks: {
            chunks: 'async',
            minSize: 30000,
            minChunks: 1,
            maxAsyncRequests: 5,
            maxInitialRequests: 3,
            name: false,
            cacheGroups: {
                vendor: {
                    name: 'vendor',
                    chunks: 'initial',
                    priority: -10,
                    reuseExistingChunk: false,
                    test: /node_modules\/(.*)\.js/
                },
            }
        }
    },
    plugins: [
        new CleanWebpackPlugin(),
    ],
})

相关推荐