使用webpack配置一个小型vuecli脚手架

17次阅读

共计 6573 个字符,预计需要花费 17 分钟才能阅读完成。

简介

使用 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.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(),
    ],
})

正文完
 0