使用webpack配置一個小型vue-cli腳手架

簡介

使用vue的朋友都是知道vue-cli,他是一個基於webpack的vue腳手架,經過vue-cli配置好一整套環境能夠更快的開發,從而提升了工做效率。而咱們能夠學習它的一些配置能夠熟悉webpack的構建流程,從而更好的開發,本文講述瞭如何配置一個小型的vue-cli腳手架。css

項目地址: mini-vue-clihtml

webpack開發環境基本配置

項目初始化

參考webpack文檔vue

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-clinode

npm install --save-dev webpack-cli
文件目錄結構

clipboard.png

webpack.common.jswebpack

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.jsgit

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.jsgithub

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

package.jsonweb

{
  "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資源vue-router

管理資源文件插件-loader

安裝資源管理插件loader

上面的項目初始化只能對js進行編譯打包,不能識別css、圖片等資源,這時候須要進行安裝loader插件進行資源管理。vue-cli

安裝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...
http://www.javashuo.com/article/p-trqitufd-gp.html

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(),
    ],
})
相關文章
相關標籤/搜索