分类
svg

Webpack Plugins 构造组件库使用的API

webpack-node-externals

const nodeExternals = require('webpack-node-externals');
...
module.exports = {
    ...
    target: 'node', // in order to ignore built-in modules like path, fs, etc.
    externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
    ...
};

组件库内不包含node_modules,减少组件体积

VueLoaderPlugin

const VueLoaderPlugin = require('vue-loader/lib/plugin');
 module: {
    rules: [
      {
        test: /\.(jsx?|babel|es6)$/,
        include: process.cwd(),
        exclude: config.jsexclude,
        loader: 'babel-loader'
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          compilerOptions: {
            preserveWhitespace: false
          }
        }
      }
    ]
  },
  plugins: [
    new ProgressBarPlugin(),
    new VueLoaderPlugin()
  ]

没有使用vue-cli创建项目时又要用到vue需要此plugin

terser-webpack-plugin

const TerserPlugin = require('terser-webpack-plugin');
optimization: {
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          output: {
            comments: false
          }
        }
      })
    ]
  },

压缩js代码并去掉注释

分类
svg

svg sprite

给svg文件一个名字,方便vue使用svg

文件存放地址

src->assets->svg-icons

qi ye wei xin jie tu 16104356734716 - svg sprite

在项目中引入文件

src->assets->svg-icons->index.js

const requireAll = requireContext => requireContext.keys().map(requireContext);
const req = require.context('./icons', false, /\.svg$/);
requireAll(req);
export default req;

main.js

import '@/assets/svg-icons';

对引入的svg文件进行配置

vue.config.js

function resolve(dir) {
  return path.join(__dirname, dir);
}
const vueConfig = {
  chainWebpack: (config) => {
    // svg
    const svgRule = config.module.rule('svg');
    svgRule.uses.clear();
    svgRule.include
      .add(resolve('src/assets/svg-icons/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'e2-[name]',
      })
      .end();
};
module.exports = vueConfig;

做一个svg组件然后引用

<template>
  <svg aria-hidden="true"
    class="svg-icon">
    <use :xlink:href="icon"></use>
  </svg>
</template>

<script>
export default {
  name: 'e2-svg',
  props: {
    name: {
      type: String,
      required: true,
    },
  },
  computed: {
    icon() {
      return `#e2-icon_${this.name}`;
    },
  },
};
</script>
<style scoped>
  .svg-icon{
    width:1em;
    height:1em;
    vertical-align:-.09em;
    margin-right:.2em;
  }
</style>

如何使用

<e2-svg name="burse"></e2-svg>

注意事项:name不是icon_burse,因为经过webpack处理,svg文件暴露除了id=“e2-icon_burse”,组件上用的是e2-icon_${this.name},所以name=“burse”