使用Vuepress快速建站

151 阅读2分钟

Vue Press Demo

基于Vue Press快速建站的一个工具示例

项目地址

快速上手

安装vuepress

在已存在的文件夹(或者mkdir vuepress-demo && cd vuepress-demo) (如果是新的文件夹,需要进行初始化yarn init或者npm init)

yarn add -D vuepress # npm install --save vuepress

创建docs文件夹

mkdir docs

同时在你的文件夹下手动新建一个REAMD.md文件(or echo '# Hellow World' > docs/README.md)

添加运行脚本

package.json

{
    "scripts": {
        "docs:build": "vuepress build docs --dest dist",
        "docs:dev": "vuepress dev docs",
    }
}

到此,你便可以在localhost:8080看到你的第一篇文档了

配置侧边栏

在docs下新建.vuepress文件夹,用来放置配置文件

新建config.js

module.exports = {
    title: 'ssVue Pre Demo',
    description: 'Just playing around',
    themeConfig: {
        sidebar: [
            ['/', 'Vue Press Demo'], // 对应的是根目录的README.md文件
        ],
    },
};

你也可以采取对象形式的配置

注意:当路径以/结尾时会查找该目录下的README.md,否则找路径下对应的your-file-name.md文件

    sidebar: [
        {
            title: 'Vue Press Demo',
            path: '/',
        },
        {
            title: '二级菜单',
            path: '/second-menu/',
            children: [
                {
                    title: '二级菜单x1',
                    path: '/second-menu/one',
                },
            ]
        }
    ]

静态组件

因为VuePress采用webpack进行打包和启动dev服务,你也可以直接在文档里编写需要服用的组件,采用.vue文件的写法,

.vue组件

<div>
I'm static Vue Component
</div>

对应的md文档

<your-own-component />

引入第三方库

你还可以在你的组件中使用第三方库,以element-ui举例

(docs/.vuepress/enhanceApp.js)

//element-ui
import Element from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
// 使用异步函数也是可以的
export default ({
    Vue, // VuePress 正在使用的 Vue 构造函数
//     options, // 附加到根实例的一些选项
//     router, // 当前应用的路由实例
//     siteData, // 站点元数据
//     isServer // 当前应用配置是处于 服务端渲染 或 客户端
  }) => {
//     // ...做一些其他的应用级别的优化
    Vue.use(Element);
};

便可以在你自己的组件中使用,以element-ui中的el-button为例

<div>Test Element Static Import Component
    <el-button type="success">按钮</el-button>
</div>

动态组件

当你引用第三方库报错window or document等dom对象为undefined时,或者是自己的组建需要使用window or document等dom对象时,便需要使用动态组件引用所需要的库了,以element-ui为例

export default {
    data() {
        return {
            dynamicComponentName: '',
        };
    },
    mounted() {
        import('element-ui').then(module => {
            this.dynamicComponentName = module.Button;
        });
    },
};
<component
    v-if="dynamicComponentName"
    :is="dynamicComponentName"
>
    动态引入按钮
</component>

打包

直接使用yarn docs:build便可

注意sidebar中配置的路径必须全部存在,否则客户端在渲染的时候会报undefined错误