准备
nodejs 18
pnpm
https://vitejs.cn/
开始
pnpm init
pnpm add -D vite
新建index.html
<!DOCTYPE html>
<html lang="zh">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>从零开始搭建vite环境</title>
</head>
<body><h1>Hello World</h1>
</body>
</html>
修改package.json
{"name": "vitestu01","version": "1.0.0","description": "","main": "index.html","scripts": {"dev": "vite","build": "vite build"},"keywords": [],"author": "","license": "ISC","devDependencies": {"vite": "^5.3.3"}
}
输入pnpm run dev
新建src目录
src目录下新建main.js,安装jquery插件
pnpm add jquery
修改index.html
<script type="module" src="/src/main.js"></script>
修改package.json,增加type
"type": "module",
如果直接访问js则会报错
安装scss
pnpm add -D sass
src下新建scss文件夹,该文件夹下新建index.scss
$font-color:#f00;body{h1{color: $font-color;}
}
修改main.js
import $ from 'jquery';
import '@/scss/index.scss';$(function (){console.log("初始化成功");
})
新增vite.config.js
import $ from 'jquery';
import '@/scss/index.scss';$(function (){console.log("初始化成功");
})
如果想定义全局变量,可以在scss下新建global.scss
$bg-color:#0f0;
修改index.scss
$font-color:#f00;body{h1{color: $font-color;background: $bg-color;}
}
修改vite.config.js
import { defineConfig } from 'vite'
// path报错安装 @types/node
import path from 'path'// https://vitejs.dev/config/
export default defineConfig({plugins: [],resolve: {alias: {'@': path.resolve('./src'),},},// scss全局变量的配置css: {preprocessorOptions: {scss: {javascriptEnabled: true,additionalData: '@import "@/scss/global.scss";'}}}
})
重新启动编译即可
打包
pnpm run build
jquery和自己写的代码都一块打包了,html中单独引入jQuery cdn链接即可
import { defineConfig } from 'vite'
// path报错安装 @types/node
import path from 'path'// https://vitejs.dev/config/
export default defineConfig({plugins: [],resolve: {alias: {'@': path.resolve('./src'),},},// scss全局变量的配置css: {preprocessorOptions: {scss: {javascriptEnabled: true,additionalData: '@import "@/scss/global.scss";'}}},build:{rollupOptions:{external: ['jquery'],output: {globals: {jquery: 'jQuery',},},}}
})
然后打包即可