vue-cli 搭建项目之 项目创建和基本配置

5,510 阅读6分钟

vue-cli官方文档

vue-cli 搭建项目之 项目创建和常规配置

项目创建

注意: 需要node环境,记得安装nodejs

环境 win10

  $ npm -v
  6.13.4
  
  $ node -v
  v12.16.0
  
  $ vue -V
  @vue/cli 4.4.6

全局安装 vue命令行工具

    npm install -g @vue/cli
    
    // 安装后 输入以下命令 查看版本 说明安装成功
    
    vue -V

    @vue/cli 4.4.6

创建项目

执行命令 vue create 项目名称

    $ vue create 项目名称
    
    ? Please pick a preset:    // 选择预设(使用箭头键)
      default (babel, eslint)  
    > Manually select features // 回车

enter后,进入手动选择配置 ,有以下Installed CLI Plugins选项(注:空格单选,a全选,i反向全选)

   ? Please pick a preset: Manually select features
   ? Check the features needed for your project: 
    (*) Babel// 语法编译 向后兼容
    ( ) TypeScript // .ts
    (*) Progressive Web App (PWA) Support // 渐进式网页应用        
    (*) Router // 路由
    (*) Vuex // 状态管理
    (*) CSS Pre-processors //  CSS 预处理器
    (*) Linter / Formatter // 语法检查
   >(*) Unit Testing // 单元测试  以开发角度
    ( ) E2E Testing // 集成测试  以用户角度

选择路由是否是使用 history模式

    ? Please pick a preset: Manually select features
    ? Check the features needed for your project: Babel, PWA, Router, Vuex, CSS Pre-processors, Linter, Unit, E2E
    ? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) Y

选择 选择一个CSS预处理器

  ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): (Use arrow keys)
  > Sass/SCSS (with dart-sass)
    Sass/SCSS (with node-sass)
    Less
    Stylus

选择 代码验证

    ? Pick a linter / formatter config: (Use arrow keys)
      ESLint with error prevention only
      ESLint + Airbnb config
      ESLint + Standard config
    > ESLint + Prettier (代码验证+风格)

选择 保存就检查代码

    ? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
    >(*) Lint on save
     ( ) Lint and fix on commit

选择单元测试解决方案 Jest

    ? Pick a unit testing solution: 
      Mocha + Chai
    > Jest

选择一个E2E测试解决方案 Cypress

   ? Pick a E2E testing solution: (Use arrow keys)
   > Cypress (Chrome only)
     Nightwatch (WebDriver-based)

选择配置内容为 专用配置文件

    ? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? (Use arrow keys)
    > In dedicated config files
      In package.json

保存配置

    ? Save this as a preset for future projects? (y/N) Y
    ? Save preset as: test // 将预设另存为指定一个名字
    
    // 之后再创建项目时 直接加载这个预设配置
    // 例如  vue create --preset test test

创建完成后进入项目执行以下命令运行项目

    cd 项目/
    npm run serve

目录说明

    ├─node_modules // npm包文件
    ├─public
    │  └─index.html // 模板文件
    │  └─img
    │      └─icons
    ├─src
    │  ├─assets // 静态资源
    │  ├─components // 公共组件
    │  ├─router // 路由
    │  ├─store // 状态
    │  ├─views // 视图
    │  ├─App.vue // 主vue模块,项目主组件
    │  ├─main.js // 入口文件 初始化vue实例
    │  └─registerServiceWorker.js // 离线缓存
    ├─.browserslistrc //浏览器兼容
    ├─.eslintrc.js // 代码检测工具
    ├─.eslintignore // 配置代码检测忽略文件 (需自行创建)
    ├─.gitignore // git 忽略文件配置
    ├─babel.config.js // 工具链 语法编译 向后兼容
    ├─package.json // 模块基本信息项目开发所需要的模块 版本 项目名称
    ├─package-lock.json // npm install后的产物,记录当前实际安装的 npm包的版本和来源
    ├─vue.config.js // 保存vue配置的文件,可以用于设置代理,打包配置等(需自行创建)
    ├─tests // 单元测试
    │  └─unit
    │     └─example.spec.js // 默认的单元测试例子
    ├─jest.config.js // 单元测试配置
    ├─README.md // markdown格式的项目说明文档
    ├─.env // 在所有的环境中被载入,但优先级别最低 (需自行创建)
    ├─.env.development // 开发环境配置(需自行创建)
    ├─.env.test // 测试环境配置(需自行创建)
    ├─.env.production // 生产环境配置(需自行创建)

基本配置

环境变量和模式

环境变量

可以在项目根目录下创建配置文件

配置文件创建规则和载入规则 如下

    .env                # 在所有的环境中被载入
    .env.local          # 在所有的环境中被载入,但会被 git 忽略
    .env.[mode]         # 只在指定的模式中被载入
    .env.[mode].local   # 只在指定的模式中被载入,但会被 git 忽略

一个环境配置文件中的内容只包含环境变量的“键=值”对:

  VUE_APP_SECRET=secret
  VUE_APP_BASE_API = http://192.168.0.151/login

模式

模式是 Vue CLI 项目中一个重要的概念。默认情况下,一个 Vue CLI 项目有三个模式:

  • development 模式用于 vue-cli-service serve // 开发环境
  • production 模式用于 vue-cli-service build 和 vue-cli-service test:e2e // 生产环境(正式环境)
  • test 模式用于 vue-cli-service test:unit // 测试环境

这里的作用是为了方便项目开发过程中的实际需要,如:不同环境的接口地址可能不一样

修改package.json 下方 添加时 //和后面的注释记得删掉 不然会报错 --mode 指定模式

    "scripts": {
        "serve": "vue-cli-service serve", // 默认读 .env.development 的配置
        "test": "vue-cli-service serve --mode test", // .env.test
        "production": "vue-cli-service serve --mode production",  // .env.production
        "build:dev": "vue-cli-service build --mode development",  // .env.development
        "build:test": "vue-cli-service build --mode test", // .env.test
        "build": "vue-cli-service build", // 默认读的 .env.production 的配置
        "test:unit": "vue-cli-service test:unit",
        "lint": "vue-cli-service lint"
    },

环境变量和模式

代码检测工具 ESLint

ESLint官网

env

extends

rules

配置

.eslintrc.js

    module.exports = {
      // 限制到当前目录下的项目
      root: true,
      // 可用的环境变量
      env: {
        browser: true, // 浏览器环境中的全局变量
        node: true, // Node.js 全局变量和 Node.js 作用域。
        es6: true, // 启用除了 modules 以外的所有 ECMAScript 6 特性
      },
      // 继承规则
      extends: ["plugin:vue/essential", "eslint:recommended", "@vue/prettier"],
      parserOptions: {
        parser: "babel-eslint"
      },
      // 定义规则
      rules: {
        "no-console": process.env.NODE_ENV === "production" ? "warn" : "off", // 是否禁用 console
        "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off" // 是否禁用 debugger
        ...// 更多规则配置可根据自己项目实际需要参考方rules链接 自行配置
      },
      // 为单元测试特定类型文件指定处理器
      overrides: [
        {
          files: [
            "**/__tests__/*.{j,t}s?(x)",
            "**/tests/unit/**/*.spec.{j,t}s?(x)"
          ],
          env: {
            jest: true
          }
        }
      ]
    };

.eslintignore

    build/*.js
    
    src/assets
    
    public

Visual Studio Code + ESLint

配置好.eslintrc.js后

打开Visual Studio Code下载插件

vue.config.js

详细配置说明


    "use strict";
    const path = require("path");
    
    function resolve(dir) {
      return path.join(__dirname, dir);
    }
    
    const name = "iwhao simple"; // title 网站标题
    
    // 默认端口
    // mac 下非root用户是无法使用小于1024的常用端口 运行 npm run serve时 记得加 sudo
    const port = process.env.port || process.env.npm_config_port || 80;
    
    module.exports = {
      publicPath: "/", // 站点根目录路径
      outputDir: "dist", // 生产环境构建文件的目录
      assetsDir: "static", // 放置生成的静态资源的目录
      lintOnSave: process.env.NODE_ENV === "development",
      productionSourceMap: false, // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建
      devServer: {
        port: port, // 端口
        open: true, // 运行完是否自动打开浏览器
        // 出现编译器错误或警告时,在浏览器中显示全屏覆盖。是否显示警告和错误:
        overlay: {
          warnings: false, // 警告
          errors: process.env.ENV !== "master" // 错误
        }
      },
      configureWebpack: {
        name: name, // 网站标题名
        resolve: {
          alias: {
            "@": resolve("src") // import '@' 相当于 import '/src'
          }
        }
      },
      // 配置进行更细粒度的修改
      chainWebpack(config) {
        config.plugins.delete("preload");
        config.plugins.delete("prefetch");
    
        // set svg-sprite-loader
        config.module
          .rule("svg")
          .exclude.add(resolve("src/icons"))
          .end();
        config.module
          .rule("icons")
          .test(/\.svg$/)
          .include.add(resolve("src/icons"))
          .end()
          .use("svg-sprite-loader")
          .loader("svg-sprite-loader")
          .options({
            symbolId: "icon-[name]"
          })
          .end();
    
        // set preserveWhitespace
        config.module
          .rule("vue")
          .use("vue-loader")
          .loader("vue-loader")
          .tap(options => {
            options.compilerOptions.preserveWhitespace = true;
            return options;
          })
          .end();
    
        config
          // https://webpack.js.org/configuration/devtool/#development
          .when(process.env.NODE_ENV === "development", config =>
            config.devtool("cheap-source-map")
          );
    
        config.when(process.env.NODE_ENV !== "development", config => {
          config
            .plugin("ScriptExtHtmlWebpackPlugin")
            .after("html")
            .use("script-ext-html-webpack-plugin", [
              {
                // `runtime` must same as runtimeChunk name. default is `runtime`
                inline: /runtime\..*\.js$/
              }
            ])
            .end();
          config.optimization.splitChunks({
            chunks: "all",
            cacheGroups: {
              libs: {
                name: "chunk-libs",
                test: /[\\/]node_modules[\\/]/,
                priority: 10,
                chunks: "initial" // only package third parties that are initially dependent
              },
              elementUI: {
                name: "chunk-elementUI", // split elementUI into a single package
                priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
              },
              commons: {
                name: "chunk-commons",
                test: resolve("src/components"), // can customize your rules
                minChunks: 3, //  minimum common number
                priority: 5,
                reuseExistingChunk: true
              }
            }
          });
          config.optimization.runtimeChunk("single");
        });
      }
    };

我的博客

我的掘金

我的简书

Laravel China

我的微信公众号
我的微信公众号