vue+vant初始化h5项目

785 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第3天,点击查看活动详情

创建Vue项目

vue create hello-world

配置rem页面自适应

  • 安装postcss-pxtorem和amfe-flexible
npm i postcss-pxtorem -S
npm i amfe-flexible -S
  • 配置
  1. 配置postcss.config.js文件
const pxtorem = require('postcss-pxtorem')
const autoprefixer = require('autoprefixer')
module.exports = {
  plugins: [
    autoprefixer(),
    pxtorem({
      rootValue: 37.5,
      propList: ['*'],
    }),
  ],
}
  1. 在main.js中引入amfe-flexible
import 'amfe-flexible';

安装vant

npm i vant -S
  • 安装插件 在非 vite 的项目中,可以通过 babel 插件来实现按需引入组件。我们需要安装 babel-plugin-import 插件,它会在编译过程中将 import 语句自动转换为按需引入的方式。
npm i babel-plugin-import -D
  • 配置插件 在.babelrc 或 babel.config.js 中添加配置:
{ "plugins": 
    [
        [ "import",
            { 
                "libraryName": "vant", 
                "libraryDirectory": "es", 
                "style": true 
            }
        ]
    ]
}
  • 按需引入组件 在代码中直接引入 Vant 组件,插件会自动将代码转化为按需引入的形式。
<template>
    <van-button type="primary">主要按钮</van-button>
    <van-button type="success">成功按钮</van-button> 
    <van-button type="default">默认按钮</van-button> 
    <van-button type="warning">警告按钮</van-button> 
    <van-button type="danger">危险按钮</van-button>
</template>
<script>
import { Button } from 'vant'
export default defineComponent({
  components: {
    [Button.name]: Button,
  },
</script>
  • ts配置插件 如果你在使用 TypeScript,可以使用 ts-import-plugin 实现按需引入。
npm i ts-import-plugin -D
const merge = require('webpack-merge');
const tsImportPluginFactory = require('ts-import-plugin');

module.exports = {
  parallel: false,
  outputDir: '../docs',
  publicPath: process.env.NODE_ENV === 'production' ? '/vant-demo/' : '/',
  chainWebpack: config => {
    config.module
      .rule('ts')
      .use('ts-loader')
      .tap(options => {
        options = merge(options, {
          transpileOnly: true,
          getCustomTransformers: () => ({
            before: [
              tsImportPluginFactory({
                libraryName: 'vant',
                libraryDirectory: 'es',
                style: true
              })
            ]
          }),
          compilerOptions: {
            module: 'es2015'
          }
        });
        return options;
      });
  }
};

以上配置完成就可以开发h5项目了,完毕!