使用@vue/cli4脚手架,从零开始搭建typescript版的UI库

1. 全局安装@vue/cli4

官网地址:https://cli.vuejs.org/zh/guid...

npm install -g @vue/cli
# OR
yarn global add @vue/cli

vue --version
@vue/cli 4.5.13 #当前版本

2.构建项目

# 创建项目totoro
vue create totoro

# 配置选项
Vue CLI v4.5.13
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, TS, Router, CSS Pre-processors, Linter, Unit
? Choose a version of Vue.js that you want to start the project with 2.x
? Use class-style component syntax? Yes
? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Yes
? Use history mode for router? (Requires proper server setup for index fallback in production) No
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with dart-sass)
? Pick a linter / formatter config: Prettier
? Pick additional lint features: Lint on save
? Pick a unit testing solution: Jest
? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
? Save this as a preset for future projects? Yes
? Save preset as: vuecl4_vue2_ts
? Pick the package manager to use when installing dependencies: Yarn

3.简单配置

vscode 保存自动格式化

# vscode settings.json文件
"editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
}

yarn serve时自动打开浏览器

# 项目根目录新建vue.config.js配置文件

module.exports = {
  devServer: {
    open: true,// 启动项目时自动打开浏览器
  },
};

4.目录结构设计

  • packages: 组件源码
  • website: 原src目录,改为组件文档官网,展示示例
  • website/docs: 组件文档和示例代码 markdown格式
  • src: 组件公用工具函数
  • src/theme: 组件样式文件夹(组件所有样式统一放这里)
  • src/index.ts: 组件统一导出入口文件(整体导出,全量包)

5.修改vue.config.js配置

# vue.config.js

// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require("path");

module.exports = {
  devServer: {
    open: true,
  },
  pages: {
    index: {
      // page 的入口
      entry: "website/main.ts",
      // 模板来源
      template: "public/index.html",
      // 在 dist/index.html 的输出
      filename: "index.html",
      // 当使用 title 选项时
    },
  },

  configureWebpack: {
    resolve: {
      // 设置别名
      alias: {
        "totoro-ui": path.join(__dirname, "./"),
        packages: path.join(__dirname, "./packages"),
        "@": path.join(__dirname, "./website"),
        main: path.join(__dirname, "./src"),
      },
    },
  },
  // 扩展 webpack 配置,使 packages 加入编译
  chainWebpack: (config) => {
    config.module
      .rule("js")
      .include.add(path.resolve(__dirname, "packages"))
      .end()
      .use("babel")
      .loader("babel-loader")
      .tap((options) => {
        // 修改它的选项...
        return options;
      });
  },
};

dragonishare
157 声望3 粉丝