webpack(三)

235 阅读1分钟

和VUE的接合

npm install vue vue-loader vue-template-compiler vue-property-decorator --save

在 webpack.base.js 中配置

// 引入
const { VueLoaderPlugin } = require('vue-loader');
 module: {
        rules: [
            {
                test:    /\.vue$/,
                loader:  'vue-loader',
            },
        ...
        ]
    ...
},
plugins: [
    new VueLoaderPlugin(),
    ...
]

src 下新建一个 index.vue。

<template>
    <div id='box'>我是VUE</div>
</template>
<script>
export default {
}
</script>
<style lang="scss" scoped>
    #box{
        color: red;
    }
</style>

修改 index.js

import Vue from 'vue';
import App from './index.vue' 
let vm = new Vue({
    el:'#root',
    render:h=>h(App)
})

运行一下

一些优化

优化webpack的插件,它要和 glob 打包来用,glob的作用是搜索文件,将没有用到的就不打包进去

npm install purgecss-webpack-plugin glob --save-dev

此处是在 webpack.prod.js 中配置的

// 主要就是查找匹配的文件
const glob = require('glob'); 
// 主要作用是删除无意义的css,它不能在style中删除,只能配合 mini-css-extract-plugin
const PurgeCssWebpackPlugin = require('purgecss-webpack-plugin');
// let paths = glob.sync("../src/**/*"); // 正则表示 src 目录下的任意文件夹下的任意目录
// glob.sync("../src/**/*",{nodir:true}); // nodir 表示不需要找目录,那就是只找单文件
...
plugins:[
    // 有毛病 No content provided.
    new PurgeCssWebpackPlugin({
        // 正则表示 src 目录下的任意文件夹下的任意目录
        // nodir 表示不需要找目录,那就是只找单文件
        paths:glob.sync("../src/**/*")
    }),
]
...

再来看看怎么优化图片

npm install image-webpack-loader --save-dev
{
    test: /\.(jpg|png|gif|jpeg)$/,
    use: [
        {
            loader: 'url-loader',
            // 优化 如果大于100k的图片会默认使用file-loader
            options: {
                name: 'image/[contentHash].[ext]', // 打包放到image目录下
                limit: 1024,
            }
        },
        !isDev && {
            // 没作用 ?
            loader:'image-webpack-loader',
            options: {
                mozjpeg: {
                  progressive: true,
                  quality: 65
                },
                // 是否禁 png 压缩
                optipng: {
                  enabled: false,
                },
                pngquant: {
                  quality: [0.65, 0.90], // 65%-90%之间
                  speed: 4
                },
                gifsicle: {
                  interlaced: false,
                },
                // the webp option will enable WEBP
                webp: {
                  quality: 75
                }
              }
        }
    ]
},