zoukankan      html  css  js  c++  java
  • webpack搭建vue3教程-超级篇

    webpack搭建vue3教程-超级篇

    一.配置vue-router:

    1.安装依赖:

    npm install vue-router@4 -S

    2.配置router:

    src/router/index.js

    import { createRouter, createWebHistory } from "vue-router";
    import Home from './Home.vue';
    import Me from './Me.vue';
    
    const routerHistory = createWebHistory();
    const router = createRouter({
        history: routerHistory,
        routes: [
            {
                path: '/home',
                name: 'Home',
                component: Home
            },
            {
                path: '/me',
                name: 'Me',
                component: Me
            }
        ]
    });
    
    export default router;

    3.使用router:

    在index.js导入router:

    import router from './router.js';
    
    createApp(App).use(router).mount('#app')

    二.配置vuex

    1.安装依赖:

    npm install vuex@next -S

    2.配置:

    src/store/index.js

    import { createStore } from "vuex";
    
    const store = createStore({
        state: {
            name: 'vuex'
        },
        getters: {},
        actions: {},
        mutations: {},
        modules: {}
    });
    
    export default store;

    3.使用:

    import store from "./store/index.js";
    
    createApp(App).use(router).use(store).mount('#app')

    三.使用ui框架(vant):

    1.安装依赖:

    npm install vant@next -S

    2.按需导入:

    npm i babel-plugin-import ts-import-plugin -D

    3.配置:

    js版本

    // babel.config.js
    module.exports = {
      plugins: [
        [
          'import',
          {
            libraryName: 'vant',
            libraryDirectory: 'es',
            style: true,
          },
          'vant',
        ],
      ]
    };

    ts版本

    const tsImportPluginFactory = require('ts-import-plugin');
    module.exports = {
      // ...
      module: {
        rules: [
          {
            test: /.ts$/,
            use: [
              {
                loader: 'ts-loader',
                options: {
                  transpileOnly: true,
                  getCustomTransformers: () => ({
                    before: [
                      tsImportPluginFactory({
                        libraryName: 'vant',
                        libraryDirectory: 'es',
                        style: (name) => `${name}/style/less`,
                      }),
                    ],
                  }),
                  compilerOptions: {
                    module: 'es2015',
                  },
                }
              },
            ],
            exclude: /node_modules/
          },
          // ...
        ],
      }
    };

    四.rem布局适配

    1.安装依赖:

    npm install lib-flexible  -S
    npm install postcss-pxtorem -D

    2.配置:

    //.postcssrc.js
    module.exports = {
        plugins:{
            // autoprefixer: {
            //     browsers: ['Android >= 4.0', 'iOS >= 8']
            // },
            'postcss-pxtorem': {
                // rootValue: 37.5, // Vant 官方根字体大小是 37.5
                rootValue({file}) {
                    return file.indexOf('vant') !== -1 ? 37.5 : 75
                },
                propList: ['*'],
                selectorBlackList: ['.norem'] // 过滤掉.norem-开头的class,不进行rem转换
            }
        },
    }
    // package.json
    {
      // ...
      "browserslist": [
        "> 1%",
        "last 2 versions",
        "not dead",
        "Android >= 4.0",
        "iOS >= 8"
      ]
    }

    3.使用:

    //  src/index.js 
    import 'lib-flexible/flexible';

    五.打包友好提示:

    1.安装依赖: 报错

    npm install friendly-errors-webapck-plugin node-notifier -D

    2.配置:

    const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
    const notifier = require('node-notifier');
    const icon = path.join(__dirname, 'public/icon.jpg');
    
    
    new FriendlyErrorsWebpackPlugin({
                onErrors: (severity, errors) => {
                    notifier.notify({
                        title: 'webpack 编译失败了~',
                        message: `${severity} ${errors[0].name}`,
                        subtitle: errors[0].file || '',
                        icon,
                    });
                },
            })

    六.分析打包文件大小:

    1.安装依赖:

    npm install webpack-bundle-analyzer -D

    2.配置:

    const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
    
    
     new BundleAnalyzerPlugin(),

    七.打包速度:

    1.安装依赖:报错

    npm install speed-measure-webpack5-plugin -D

    2.配置:

    const SpeedMeasureWebpack5Plugin = require('speed-measure-webpack5-plugin');
    const smw = new SpeedMeasureWebpack5Plugin();
    
    module.exports = smw({
        // options
    })

    八.缩小打包范围:

    • exclude:排除某些文件,类似黑名单
    • include:包含文件,类似白名单
    • 优先度:exclude >>> include

    1.配置:

     exclude: /node_modules/,
            include: path.resolve(__dirname, 'src')

    九.配置缓存:

    • 默认babel-loader中可以配置缓存
    • 其他loader如果要缓存,需要下载cache-loader

    1.安装依赖:报错 

    npm install cache-loader -D

    2.配置:

    //babel-loader直接可以配置
    {
                    test: /.js$/,
                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-env'],
                             cacheDirectory: true
                        }
                    },
                     exclude: /node_modules/,
                     include: path.resolve(__dirname, 'src')
                },
    //    其他loader中需要安装cache-loader
    {
                    test: /.css$/,
                    use: [
                        'cache-loader',
                        'style-loader',
                        'css-loader'
                    ]
                },

    十.代码规范:

    1.js代码规范:eslint

    配置:.eslintrc.js

    //.eslintrc.js
    module.exports = {
      root: true, // 此项是用来告诉eslint找当前配置文件不能往父级查找
      env: {
        node: true, // 此项指定环境的全局变量,下面的配置指定为node环境
      },
      extends: ['plugin:vue/recommended', '@vue/prettier'],
      rules: {
        'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
        'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
        'vue/no-v-html': 'off',
      },
      parserOptions: {
        parser: 'babel-eslint',
        parser: 'babel-eslint',
        ecmaVersion: 7,
        sourceType: 'module',
        ecmaFeatures: {
          // 添加ES特性支持,使之能够识别ES6语法
          jsx: true,
        },
      },
      overrides: [],
    };

    配置.eslintignore

    //.eslintignore
    src/assets
    src/icons
    public
    dist
    node_modules

    代码格式化:prettier

    //prettier.config.js
    module.exports = {
      printWidth: 80,
      tabWidth: 2,
      useTabs: false,
      semi: false,
      singleQuote: true,
      quoteProps: 'as-needed',
      jsxSingleQuote: false,
      trailingComma: 'es5',
      bracketSpacing: true,
      jsxBracketSameLine: false,
      arrowParens: 'always',
      htmlWhitespaceSensitivity: 'ignore',
      vueIndentScriptAndStyle: true,
      endOfLine: 'lf',
    }

    2.css代码规范:stylelint

    配置:.stylelintrc.js

    //.stylelintrc.js
    module.exports = { extends: ['stylelint-config-recess-order', 'stylelint-config-prettier'], }

    配置:.editorconfig

    root = true
      
    [*]
    charset = utf-8
    end_of_line = lf
    indent_size = 2
    indent_style = space
    insert_final_newline = true
    trim_trailing_whitespace = true
      
    [*.md]
    trim_trailing_whitespace = false

    3.git提交校验代码规范:

    安装依赖:

    npm install -g commitizen cz-conventional-changelog

    配置:

    //package.json
    "husky": {
          "hooks": {
            "commit-msg": "commitlint -e $GIT_PARAMS"
          }
      },

    十一.自动化测试及发布:

    为了明天能幸福,今天付出再多也不后悔。
  • 相关阅读:
    欧拉函数(线性筛)(超好Dong)
    欧拉函数(线性筛)(超好Dong)
    线性素数筛(欧拉筛)(超级好的MuBan)
    线性素数筛(欧拉筛)(超级好的MuBan)
    Fire Game (FZU 2150)(BFS)
    Fire Game (FZU 2150)(BFS)
    Fantasy of a Summation (LightOJ
    Java——接口
    Java——异常处理
    Java——数组
  • 原文地址:https://www.cnblogs.com/zlp520/p/14872630.html
Copyright © 2011-2022 走看看