Vue 3.0 Family Bucket + Vite configure development environment and production environment from scratch

In the last article we compared the differences Vitebetween and Webpack. Webpack 5.0Next, to prepare to replace the one used in the project Vite 2.0, we first set out to configure the development/production environment from scratch.

1. Initialization
  • 1. Initializationpackage.json

    npm init// Enter all the way

  • 2. Installation Vite( nodeversion requirements 14.18 +)

    yarn add vite --devornpm install vite -D

  • 3. Initialize project

    Initialization directory structure config/vite.config.jsconfiguration file, index.htmlexport file, index.jsentry file, srcdirectory source code

    Because Viteit is based ESMon HTTPrequesting to obtain the required files, so the entrance index.jsshould pay attention to:

    • 1. typeformodule
    • 2. srcThe path must use an absolute path.
      Insert image description here
  • 4. Configure packaging commands

    package.json: Here --openrefers to opening the window, -creferring to using customized configuration, -mspecifying the environment developmentorproduction

    "scripts": {
          
          
    	"dev": "vite serve -c ./config/vite.config.js -m development --open",
    	"build": "vite build -c ./config/vite.config.js -m production"
    }
    

    See more configurations:npx vite --help

    Insert image description here

2. Configuration
  • 1. Basic configuration

    Students who have configured wepback, I believe this configuration is familiar to them. Compared with webpack, the configuration is much simpler. webpackStudents who don't know how to configure it are recommended to familiarize themselves webpackwith the configuration first. Click to enter: Webpack 4.X Configure SPA single-page application from scratch

    import {
          
           defineConfig } from 'vite'
    import {
          
           resolve } from 'path'
    
    export default defineConfig({
          
          
      root: process.cwd(), // 项目根目录
      base: '/', // 项目基准路径,默认 /
      publicDir: 'public', // 静态资产的目录,默认 public
      cacheDir: 'node_modules/.vite', // esbuild预构建缓存(依赖/缓存)
      resolve: {
          
          
        // 项目别名
        alias: {
          
          
          '@': resolve(__dirname, '../src'),
          'pages': resolve(__dirname, '../src/pages')
        },
      	extensions: ['.js', '.vue', '.json'] // 引入对应的文件时可以忽略其后缀
      }
    })
    

    The development environment can be started here, because it Vitehas helped us configure the default dev server, execute it directly npm run dev, and find errors and missing esbuilddependencies, install dependenciesnpm install esbuild-windows-64 -D

    Insert image description here

    After the installation is successful, re-execute npm run devand start successfully. Because the default configuration is used here, in order to facilitate expansion, we need to reconfigure it here.dev server

    Insert image description here

  • 2. Configure the development environment
    server: {
          
          
    	 host: '0.0.0.0', // 服务器主机名,如果允许外部访问,可设置为 "0.0.0.0"
    	 port: 3000, // 服务器端口号:默认3000,如果被占用,自动切换
    	 open: true, // 是否自动打开浏览器
    	 strictPort: false, // 设为 true 时若端口已被占用则会直接退出,而不是尝试下一个可用端口
    	 force: true, //是否强制依赖预构建
    	 proxy: proxyConfig // 代理
    }
    
    // proxyConfig.js: 
    
    export default {
          
          
    	 '/api': {
          
          
    	   target: 'http://xxx.com',
    	   changeOrigin: true,
    	   rewrite: path => path.replace(/^\/api/, '')
    	 },
    	 '/socket.io': {
          
          
    	   target: 'ws://localhost:3000',
    	   ws: true
    	 }
    }
    
  • 3. Configure CSSpreprocessor and prefix

    If used sass, there is no need to download node-sassor sass-loaderpackage, just install it directly sass. Here we use less, download it directly.less

    npm i less autoprefixer postcss -D

    • Configure lesspreprocessor
      import {
              
               resolve } from 'path'
      
      export default defineConfig({
              
              
      	...
      	css: {
              
              
      		preprocessorOptions: {
              
              
      			less: {
              
              
      				  additionalData: `@import "${
                
                resolve(__dirname, '../src/assets/css/common.less')}";`, // 配置 less 全局变量
      				  javascriptEnabled: true
      			}
      		},
      		devSourcemap: true, // 在开发过程中是否启用 sourcemap
      	}
      })
      
    • Configuration autoprefixerPrefix auto-completion
      postcss.config: Configurationautoprefixer
      module.exports = {
              
              
      	"plugins": {
              
              
      	    "autoprefixer": {
              
              },
      	}
      }
      
      package.jsonConfiguration compatibility processing
      {
              
              
      	 "browserslist": [
      		 "defaults",
      		 "not ie < 11",
      		 "last 2 versions",
      		 "> 1%",
      		 "iOS 7",
      		 "last 3 iOS versions"
      	]
      }
      
      After the configuration is completed, let's take a look at the effect and take effect.
      Insert image description here
  • 4. Configure vue 3.0development environment
    • 4.1 Install dependencies

      1. Installation vueenvironment: npm i vue -D or yarn add vue --dev
      2. Installation vue plugin: npm i @vitejs/plugin-vue -D or yarn add @vitejs/plugin-vue --dev

    • 4.2 Configuration vueenvironment

      vite.config.js: viteConfiguration

      import vue from '@vitejs/plugin-vue'
      
      export default defineConfig({
              
              
      	 plugins: [
      	 	vue()
      	 ]
      })
      

      index.js: Entry file

      import {
              
               createApp } from 'vue'
      import App from './App.vue'
      const app = createApp(App)
      	
      app.mount('#root')
      

      App.vue: parent component

      <template>
      	<div class="container">
      	 {
              
              {
              
               num }}
      	</div>
      </template>
      
      <script>
      import {
              
               ref, onBeforeMount } from 'vue'
      
      export default {
              
              
      	setup() {
              
              
      	 let num = ref(0)
      	
      	 onBeforeMount(_ => {
              
              
      	   console.log(num.value)
      	 })
      	
      	 return {
              
               num }
      	}
      }
      </script>
      
      <style lang="less">
      .app {
              
              
      	font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif !important; /*网页默认字体,顺序优先级*/
      	font-size: 16px; /*网页默认字体大小*/
      	user-select: none; /*页面文字禁止选中*/
      	-webkit-font-smoothing: antialiased; /*字体进行抗锯齿渲染*/
      	-moz-osx-font-smoothing: grayscale; /*字体进行抗锯齿渲染*/
      	box-sizing: border-box !important; /*解决怪异盒模型*/
      	-webkit-backface-visibility: hidden; /*使用CSS Transforms 或者 Animations时可能会有页面闪烁的Bug*/
      	-webkit-tap-highlight-color: transparent; /*cursor为pointer时,移动端会有蓝色背景:*/
      	scroll-behavior: smooth; /*浏览器默认滚动触发时添加过渡动画*/
      	transform: translateZ(0); /*硬件加速*/
      }
      </style>
      

      Try it while running, npm run devperfect

      Insert image description here

    • 4.3 Configure vue-routerrouting

      npm i vue-router@4 -S

      router/index.jsRouting configuration, here the routing mode parameter is historynotmode , you can view its parameters from the source code

      import {
              
               createRouter, createWebHashHistory } from 'vue-router'
      
      const Home = () => import('../pages/home')
      
      const routes = [
        {
              
              
          path: '/',
          redirect: {
              
              
            path: '/Home'
          }
        },
        {
              
              
          path: '/Home',
          name: 'Home',
          component: Home
        }
      ]
      
      export default createRouter({
              
              
        history: createWebHashHistory(),
        routes,
      })
      
    • 4.4 Configuration vuexstatus management

      npm i vuex@next -S

      store/index.js: The status management module is built-in in the new version createLogger and can be introduced directly.

      import {
              
               createStore, createLogger } from 'vuex'
      import app from './module/app'
      
      export default createStore({
              
              
        modules: {
              
              
          app // 单个管理模块
        },
        plugins: [ createLogger ], // 修改 state 时打印日志
        strict: true // 严格模式,不允许直接修改 state
      })
      

      home.vue: Used by a single routing component

      <template>
        <div>Home</div>
      </template>
      
      <script>
      import {
              
               ref, onMounted } from 'vue'
      import {
              
               useStore } from 'vuex'
      
      export default {
              
              
        setup() {
              
              
          let store = useStore()
      
          onMounted(_ => {
              
              
      	  // 获取配置文件
            store.dispatch('_getConfig', {
              
               mode: 'T' })
          })
      
          return {
              
               store }
        }
      }
      </script>
      
    • 4.5 Configuration elementcomponent library

      npm install element-plus -S

      !!! During installation, the following error may be reported. This query is esbuild, bugand the processing method is: execute in the current directory:node ./node_modules/esbuild/install.js

      Insert image description here

      After executing the command, download again, perfect solution

      Insert image description here

      index.js: Introduce and use, you must pay attention to the order here, load the plug-in first, and then mount it

      import {
              
               createApp } from 'vue'
      import element from 'element-plus'
      import '@/assets/css/index.css'
      import App from './App'
      const app = createApp(App)
      
      app.use(element)
      app.mount('#root')
      

      Insert image description here

    • 5. Configure the production environment
      import {
              
               resolve } from 'path'
      
      export default defineConfig({
              
              
        ...
        build: {
              
              
      	    outDir: resolve(__dirname, '../dist'), // 指定输出路径(相对于 项目根目录)
      	    assetsDir: 'static', // 指定生成静态资源的存放路径(相对于 build.outDir)
      	    cssCodeSplit: true, // 启用 CSS 代码拆分
      	    chunkSizeWarningLimit: 500, // chunk 大小警告的限制(以 kbs 为单位)
      	    sourcemap: false // 构建后是否生成 source map 文件
        }
      })
      

      If you want to switch different configurations according to different environments, you can create them in the root directory .env.[mode], where modeis the current environment

      .env                # 所有情况下都会加载
      .env.local          # 所有情况下都会加载,但会被 git 忽略
      .env.[mode]         # 只在指定模式下加载
      .env.[mode].local   # 只在指定模式下加载,但会被 git 忽略
      

      Currently, you can also execute some specific logic based on the current environment variables.

      • import.meta.env.MODE: {string} The mode in which the application runs
      • import.meta.env.BASE_URL: {string} Basic when deploying the application URL. It is basedetermined by configuration items.
      • import.meta.env.PROD: {boolean} Whether the application is running in a production environment
      • import.meta.env.DEV: {boolean} Whether the application is running in a development environment (always the import.meta.env.PRODopposite)
3. End

At this point, a simple and practical vite+ vue 3.0project has been basically built. eslintCode specifications, vuex hooksintegration, cdnloading, Typescriptenvironment, etc. will be added later.

4. Related articles

Guess you like

Origin blog.csdn.net/Vue2018/article/details/125526656