返回
如何开发项目脚手架模板,变得更“高效”?
前端
2024-01-15 12:48:54
我们每次搭建项目都需要创建项目,然后进行一系列的基础配置,封装基础api ,配置webpack,浪费了很多时间和精力。而我们只需要用自己封装的脚手架模板就可以每次像创建vue,react那样一样简单,开发效率大大提高,有能力的还可以去封装自己的框架。
1. 先上插件依赖
{
"dependencies": {
"chalk": "^4.1.2",
"inquirer": "^8.2.4",
"ora": "^5.4.1",
"shelljs": "^0.8.5"
}
}
2. 项目的创建
/**
* 初始化package.json
*/
async function initPackage() {
const answers = await inquirer.prompt([
{
type: 'input',
name: 'name',
message: 'Project name:'
},
{
type: 'input',
name: 'description',
message: 'Project description:'
},
{
type: 'input',
name: 'author',
message: 'Author:'
}
]);
const content = JSON.stringify({
name: answers.name,
version: '1.0.0',
description: answers.description,
author: answers.author,
license: 'MIT',
scripts: {
"dev": "webpack serve --mode development",
"build": "webpack --mode production"
}
}, null, 2);
await fs.writeFile('./package.json', content, 'utf8');
}
3. 配置Webpack
/**
* 初始化webpack.config.js
*/
async function initWebpackConfig() {
const content = `
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode: 'development',
devServer: {
contentBase: './dist',
port: 3000
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
};
`;
await fs.writeFile('./webpack.config.js', content, 'utf8');
}
4. 配置.gitignore
/**
* 初始化.gitignore
*/
async function initGitIgnore() {
const content = `
node_modules
dist
.DS_Store
.env
`;
await fs.writeFile('./.gitignore', content, 'utf8');
}
5. 脚手架脚本
/**
* 创建脚手架脚本
*/
async function createScaffoldScript() {
const content = `
#!/usr/bin/env node
const chalk = require('chalk');
const inquirer = require('inquirer');
const ora = require('ora');
const shelljs = require('shelljs');
const initPackage = require('./scripts/initPackage');
const initWebpackConfig = require('./scripts/initWebpackConfig');
const initGitIgnore = require('./scripts/initGitIgnore');
async function main() {
const spinner = ora('Initializing project...').start();
await initPackage();
await initWebpackConfig();
await initGitIgnore();
spinner.succeed('Project initialized successfully!');
console.log(chalk.green('You can now run the following commands:'));
console.log(chalk.green(' npm run dev'));
console.log(chalk.green(' npm run build'));
}
main();
`;
await fs.writeFile('./scaffold.js', content, 'utf8');
}
完成以上步骤后,我们就可以使用脚手架模板来快速创建新的项目了。
在终端中运行以下命令:
npm run scaffold
系统将会询问你一些问题,比如项目名称、项目、作者等。回答完这些问题后,脚手架模板就会自动创建项目并安装必要的依赖。
总结
脚手架模板可以帮助我们快速启动新项目并提高开发效率。创建一个脚手架模板并不难,只需要掌握一些基本的技术和工具。希望这篇文章对你有帮助。