文件魔术数字_如何使用魔术脚手架自动创建文件并节省时间
文件魔术数字
Before we begin: This article uses JavaScript / Node.js example code, but you can port these concepts to any language using the right tools.
开始之前:本文使用JavaScript / Node.js示例代码,但是您可以使用正确的工具将这些概念移植到任何语言。
精彩的介绍 (An exciting intro)
Do you ever find yourself creating the same files over and over again in your projects?
您是否发现自己在项目中一遍又一遍地创建相同的文件?
I do, too.
我也做。
我的手指受伤了! (My fingers hurt!)
I’m not surprised. You’re taking work from the robots.
我不惊讶。 您正在从机器人那里接管工作。
Creating the same files repeatedly is boring and unnecessary.
重复创建相同的文件很无聊,也没有必要。
TLDR? 我知道了-这是一个演示 (TLDR? I got you — Here’s a demo)
给我看代码 (Show me the code)
I respect your sense of urgency — I’ll cut to the chase.
我尊重您的紧迫感-我会追逐。
代码 (The Code)
We want to automate file creation — that’s why you all showed up today. First, we need to identify the files we want to create.
我们希望自动化文件创建-这就是今天所有人出现的原因。 首先,我们需要确定我们要创建的文件。
I’ve been creating a lot of React components lately, so my setup revolves around that — but you can tweak this for literally anything.
最近,我一直在创建很多React组件,因此我的设置围绕着这一点进行-但您实际上可以对其进行调整。
I’ve split this into four steps. Just telling you now so you can manage your expectations. If you can’t handle anything longer than three steps, then we’re in trouble...
我将其分为四个步骤。 现在就告诉您,以便您可以管理自己的期望。 如果您不能完成超过三步的操作,那么我们就麻烦了...
步骤1:模板 (Step 1: Templates)
Set them up once and profit.
设置一次即可获利。
We need templates. I used Template Literals, but do it in whatever way makes sense to you — be creative.
我们需要模板。 我使用了Template Literals ,但是以您认为有意义的任何方式进行-发挥创意。
These are the files I’m creating every time I make a React component:
这些是我每次制作React组件时要创建的文件:
index.jsx
index.jsx
{Component}.test.js
{Component} .test.js
{Component}.sass
{Component} .sass
Note: {Component} implies string interpolation.
注意: {Component}表示字符串插值 。
I’m testing with Jest, and using the create-react-app boilerplate. I know a lot of people prefer CSS-in-JS these days — but hey. Let me know in the comments what you’re into.
我正在使用Jest进行测试,并使用create-react-app样板。 我知道现在有很多人喜欢CSS-in-JS-但是,嘿。 在评论中让我知道您的兴趣。
Anyway — Here we go:
无论如何-我们开始:
const templates = {index: name => `// @flow
import React from 'react';
import './${name}.css';
// TODO: write rest of ${name} component
const ${name} = () => (<div className="${name.toLowerCase()}"><span>rest of component</span></div>
);
export default ${name};`,test: name => `// TODO: TDD
import { shallow, render } from 'enzyme';
import renderer from 'react-test-renderer';
import React from 'react';
import ${name} from '.';
const component = <${name} />;
describe('The ${name} component', () => {it('renders correctly', () => {const wrapper = render(component);expect(wrapper.hasClass('${name.toLowerCase()}')).toBeTruthy();const tree = renderer.create(component).toJSON();expect(tree).toMatchSnapshot();});
});`,sass: name => `.${name.toLowerCase()}background: initial`,
};
That’s the messiest piece of code you’ll see here — pinky promise.
这是您在这里看到的最乱的代码-小指承诺。
So, we have an object with three properties: index, test, and sass. Each hosts a function which takes a name and returns a template with that name interpolated. Seems legit.
因此,我们有一个具有三个属性的对象:索引,测试和sass。 每个托管一个函数,该函数采用一个名称,并返回一个插有该名称的模板。 似乎是合法的。
步骤2:让我们做一些功能! (Step 2: Let’s make some functions!)
We’re using the fs module packaged with Node. It’s fab. It does many things.
我们正在使用Node附带的fs模块 。 是晶圆厂。 它做很多事情。
We’re going to use some arrow functions and a little functional programming. Don’t be scared — just go with it.
我们将使用一些箭头功能和一些功能编程 。 不要害怕-随它去吧。
The double arrow function syntax is called currying. It’s okay if it looks weird. I was freaked out when I first saw it, but it allows for super cool stuff. In fact, here’s a quick demo:
双箭头函数的语法称为currying 。 看起来很奇怪也可以。 当我第一次看到它时,我感到非常震惊,但是它可以提供超酷的东西 。 实际上,这是一个快速演示:
const fs = require('fs');const fileExists = path => file => fs.existsSync(`${path}/${file}`);const fileExistsInSrc = fileExists('/src'); // file => fs.existsSync(`${path}/${file}`)fileExistsInSrc('index.js') // true || false
So that’s currying with partial application — it’s also a closure.
因此,使用部分应用程序很麻烦 -这也是一个闭包 。
Sidebar: Hopefully nobody calls me out here on some technicality, but please do harass me in the comments if you feel the need.
补充工具栏 :希望没人在这里给我一些技术性的要求,但是如果您有需要,请在评论中骚扰我。
Let’s carry on:
让我们继续:
const fs = require('fs');const fileExists = path => file => fs.existsSync(`${path}/${file}`);const writeToPath = path => (file, content) => {const filePath = `${path}/${file}`;fs.writeFile(filePath, content, err => {if (err) throw err;console.log("Created file: ", filePath);return true;});
};
First we require fs. We need it in our life.
首先,我们需要fs 。 我们一生中都需要它。
Then we declare fileExists as a function expression.
然后,我们将fileExists声明为函数表达式 。
Finally we have another function expression called writeToPath. It takes the path and returns another function which accepts a file string and the content of that file. It then writes the file or throws an error (worst case scenario).
最后,我们还有另一个函数表达式称为writeToPath。 它采用路径并返回另一个函数,该函数接受文件字符串和该文件的内容 。 然后,它将写入文件或引发错误(最坏的情况)。
You get it right? We’re creating some files.
你说对了吗? 我们正在创建一些文件。
步骤3:认识Chokidar (Step 3: Meet Chokidar)
Fun fact: It’s a Hindi word.
有趣的事实:这是北印度语单词 。
Chowkidar — (India) watchman, caretaker, gatekeeper; one who inhabits a “chowki”, police station or guard house.
乔基达尔 -( 印度 )值班员,看守人,看门人; 居住在“ chowki”,警察局或警卫室的人。
We’re talking about the npm package though. It’s based on our new friend fs and you could use it for so many delightful things.
我们正在谈论npm软件包 。 它基于我们的新朋友fs ,您可以将其用于许多令人愉悦的事情。
It watches our files for us like a hawk.
它像鹰一样为我们监视文件。
Well not exactly like a hawk.
嗯,不完全像鹰。
It is not a bird.
它不是鸟。
Like at all.
一样。
Anyway, here’s the code…
无论如何,这是代码...
const chokidar = require("chokidar");const watcher = chokidar.watch("src/components/**", { ignored: /node_modules/ }).on("addDir", (path, event) => {const name = path.replace(/.*\/components\//, "");const goodToGo = /^[^\/_]*$/.test(name);if (goodToGo) createFiles(path, name);});
First we require it.
首先,我们需要它。
Next we define what we want to watch. I’m watching the src/components directory, but you can watch any set of paths. You can even pass an array of paths. If you don’t recognize the ** part in src/components/** — it’s called a glob pattern.
接下来,我们定义我们要观看的内容。 我正在看src / components目录,但是您可以看任何一组路径。 您甚至可以传递一系列路径 。 如果您无法识别src / components / **中的**部分,则称为glob模式 。
After that, we define what events we want to listen for. I’m only listening for adding a directory with .on(“addDir”) but you can listen for other events too.
在那之后,我们定义我们想听的事件。 我只是在监听添加带有.on(“ addDir”)的目录,但是您也可以监听其他事件 。
Next let’s extract the name of the component by replacing anything before the component name:
接下来,通过替换组件名称之前的任何内容来提取组件的名称:
src/components/Header/components/Title
becomes
变成
Title
Finally we will check that the component name passes this regex:
最后,我们将检查组件名称是否通过此正则表达式:
/^[^\/_]*$/
So as long as it doesn’t have a forward slash or underscore — it’s good to go. This avoids polluting __tests__ folders or nested/directories by mistake.
因此,只要它没有正斜杠或下划线-那就很好了。 这样可以避免错误地污染__tests__文件夹或嵌套/目录。
步骤4:是时候制作一些文件了! (Step 4: Time to make some files!)
You reached the last step. Congratulations! It’s been pretty great.
您已到达最后一步。 恭喜你! 真是太好了。
This next function is aptly named createFiles.
下一个函数恰当地命名为createFiles 。
It’s a bit messy — it could be refactored.
有点混乱-可以重构。
I apologize in advance if the code below offends you.
如果以下代码冒犯了您,我深表歉意。
Let’s dig in:
让我们深入探讨:
function createFiles(path, name) {const files = {index: "index.jsx",test: `${name}.test.js`,sass: `${name}.sass`};if (name !== "components") {const writeFile = writeToPath(path);const toFileMissingBool = file => !fileExists(path)(file);const checkAllMissing = (acc, cur) => acc && cur;const noneExist = Object.values(files).map(toFileMissingBool).reduce(checkAllMissing);if (noneExist) {console.log(`Detected new component: ${name}, ${path}`);Object.entries(files).forEach(([type, fileName]) => {writeFile(fileName, templates[type](name));});}}
}
So at the top, we declare the files object — it’s a list of file name strings which we’re injecting the name parameter into. You might have noticed that it has the same keys as the templates object. That’s important.
因此,在顶部,我们声明了files对象-这是文件名字符串的列表,我们将name参数注入其中。 您可能已经注意到,它具有与模板对象相同的键。 那很重要
The if statement is very specific to my setup. I don’t want to create my files if the new folder is called components. I am only creating components within a components sub-folder.
if语句非常特定于我的设置。 如果新文件夹称为components,我不想创建文件。 我仅在组件子文件夹中创建组件。
writeFile is our function writeToPath partially applied. It’s a function that creates a file in the given path when called with a filename and some content.
writeFile是部分应用的函数writeToPath 。 当使用文件名和某些内容调用该函数时,它将在给定路径中创建文件。
toFileMissingBool takes a file name and returns true if that file doesn’t exist in the given path. I know the function names are weird, but I promise it kind of makes more sense in a few lines.
toFileMissingBool采用文件名,如果给定路径中不存在该文件,则返回true。 我知道函数名称很奇怪,但是我保证在几行中它会更有意义。
checkAllMissing is a function that we are going to pass to reduce. It takes two booleans and returns true if both are true. This is boolean algebra. We are also using the reduce method of Array. Don’t be afraid of reduce. It’s super cool and really useful in this kind of situation.
checkAllMissing是我们将要减少的函数。 它需要两个布尔值,如果两个都为true,则返回true。 这是布尔代数 。 我们还使用Array的reduce方法。 不要害怕减少。 在这种情况下,它非常酷,而且非常有用。
Let’s talk about the variable noneExist. If it’s true, then none of the files we want to create exist in the new folder. The idea is that you don’t mess with a folder just because it doesn’t have a test file or a sass file. Maybe that folder doesn’t need one.
让我们谈谈变量noneExist 。 如果为true,则新文件夹中不存在我们要创建的文件。 这个想法是,您不会因为没有测试文件或sass文件而惹恼它。 也许那个文件夹不需要一个。
const noneExist = Object.values(files).map(toFileMissingBool) .reduce(checkAllMissing);
That’s why I created those strangely named functions above.
这就是为什么我在上面创建了那些名字奇怪的函数的原因。
We map the values in files to a boolean which represents if that file is missing or not. Then we take that array of booleans and reduce them to a single boolean value which represents whether all the files exist or not.
我们将 文件中的值映射到一个布尔值,该布尔值表示该文件是否丢失。 然后,我们采用该布尔数组并将其减小为一个布尔值,该布尔值表示所有文件是否存在。
So if they’re all true, then noneExist is also true. But if even one is false, then noneExist will be false.
因此,如果它们全部为真,则noneExist也为真。 但是,即使哪一个为假, noneExist也将为假 。
I hope you got all that. It’s a bit of a mouthful.
我希望你能得到所有。 有点大嘴巴 。
Last bit of code:
最后一点代码:
Object.entries(files).forEach(([type, fileName]) => {writeFile(fileName, templates[type](name));
});
We take the key (type) and value (fileName) and write a file in the given path with the content from the relevant template.
我们使用键( 类型)和值(fileName),并使用相关模板中的内容在给定路径中写入文件。
鳍。 (Fin.)
That picture of a sea turtle represents how free you must be feeling now you have automated everything.
这张海龟的图片代表着现在您已经自动化了一切,您必须有多自由。
If you want the whole code for auto-creating react components, it’s here.
如果您需要用于自动创建React组件的全部代码,请在此处 。
Let me know what you thought — Keep in touch.
让我知道您的想法-保持联系。
Tell me if you find any errors.
告诉我您是否发现任何错误。
Follow me on Twitter, Medium or Github.
在Twitter , Medium或Github上关注我。
翻译自: https://www.freecodecamp.org/news/how-to-create-files-automatically-and-save-time-with-magic-scaffolding-8dcd1b31483/
文件魔术数字
相关文章:

Sql Server统计报表案例
场景:查询人员指定年月工作量信息 USE [Test] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER procedure [dbo].[GetWorkLoadMain] year int, month int, UserId varchar(50) as begindeclare day varchar(50)set dayCAST(year as varchar)-RIGHT((00…

运行报表时提示输入用户名和密码
在AX2012运行报表是总是提示用户输入用户名和密码: 尝试输入登陆名和密码,点击查看报表,出现如下错误: 因为AX2012的报表使用的针对AX2012客制化的SSRS,而要求输入登录名和密码是SSRS报表的数据源设置导致的。在SSRS管…

CSS 文字,边框实现从左至右颜色渐变
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 1.文本从左至右颜色渐变 效果图: 2.边框从左至右颜色渐变 效果图: 实现代码: 1.文本从左至右颜色渐变实现代码: <!DOCTYPE html> <html>&l…

如何使用Create-React-App和自定义服务人员构建PWA
Note: This is not a primer on create-react-app or what a service worker is. This post assumes prior knowledge of both.注意:这不是create-react-app或服务工作者的入门。 这篇文章假定两者都有先验知识。 So, I recently had the opportunity to work on a…

inline-block空隙怎么解决
方法一:移除空格 元素间留白间距出现的原因就是标签段之间的空格,因此,去掉HTML中的空格,自然间距就木有了。考虑到代码可读性,显然连成一行的写法是不可取的,我们可以: <div class"spa…

php 网络请求 get请求和post请求
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 代码记录 <?php header(content-type:application:json;charsetutf8); header(Access-Control-Allow-Origin:*); //header(Access-Control-Allow-Methods:POST); header(Access-Control-Allow-He…

docker查看现有容器_如何使用Docker将现有应用程序推送到容器中
docker查看现有容器by Daniel Newton丹尼尔牛顿 如何使用Docker将现有应用程序推送到容器中 (How to shove an existing application into containers with Docker) I have finally got round to learning how to use Docker past the level of knowing what it is and does w…

巧妙使用Firebug插件,快速监控网站打开缓慢的原因
巧妙使用Firebug插件,快速监控网站打开缓慢的原因 原文 巧妙使用Firebug插件,快速监控网站打开缓慢的原因 很多用户会问,我的网站首页才50KB,打开网页用了近60秒才打开?如何解释? 用户抱怨服务器运行缓…

第二阶段第三次站立会议
昨天做了什么:写了部分购物车的功能 今天要干什么:修改后台代码的错误 遇到的困难:没有困难转载于:https://www.cnblogs.com/jingxiaopu/p/7109774.html

微信小程序生成小程序二维码 php 直接可以用
微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 小程序需要先上线才能生成二维码 HTTP请求的效果图: 小程序展示的效果图: 小程序展示二维码源码: 请求二维码图片base64路径,点击预览图片 onLoad: func…

vue和react相同点_我在React和Vue中创建了相同的应用程序。 这是区别。
vue和react相同点by Sunil Sandhu由Sunil Sandhu 我在React和Vue中创建了相同的应用程序。 这是区别。 (I created the same app in React and Vue. Here are the differences.) Having used Vue at my current workplace, I had a fairly solid understanding of how it all …

Filter(过滤器)
一、Filter过滤器(重要) Javaweb中的过滤器可以拦截所有访问web资源的请求或响应操作。 1、Filter快速入门 1.1、步骤: 1. 创建一个类实现Filter接口 2. 重写接口中方法 doFilter方法是真正过滤的。 3. 在web.xml文件中配置 …

css3实现3D立体翻转效果
1、在IE下无法显示翻转效果,火狐和谷歌可以 1 /*样式css*/2 3 .nav-menu li {4 display: inline;5 }6 .nav-menu li a {7 color: #fff;8 display: block;9 text-decoration: none;10 overflow: visible;11 line-height: 40px;12 font-…

Ant Design 入门-参照官方文档使用组件
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 先来一个按钮组件使用的对比,官方文档的(不能直接用)和实际能用的。 官网demo: import { Table, Divider, Tag } from antd;const columns = [{title: Name,dataIndex: name,key: name,render: text =…

如何用JavaScript的回调函数做出承诺
by Adham El Banhawy由Adham El Banhawy 如何用JavaScript的回调函数做出承诺 (How to make a Promise out of a Callback function in JavaScript) Back-end developers run into challenges all the time while building applications or testing code. As a developer who …

VMware里的linux系统里的命令行里会有bee的声音,要如何关掉
VMware里的linux系统里的命令行里会有bee的声音,要如何关掉 取消bell报警声的方法:登陆linux系统vi /etc/inputrc找到set bell-style none 将前面的#去掉,之后重启系统即可解决声音问题若不见效可以通过下面的方式解决下bell-styl…

React-Todos
最近学完React的最基本概念,闲下来的时候就自己写了一个Todo-List的小应用。这里做个简略的说明,给想好好学React的新手看。 React-Todo 学习前提 这里我用了webpackb做了babel和JSX预处理和模块打包。所以对React和一些ES2015(ES6࿰…

Ant Design 入门-引用自己命名的组件
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 自己创建的组件:代码 import { Table, Divider, Tag } from antd; import React, { Component } from react; export default class My_Table extends Component {render() {const columns = [{title: …

迷宫出路代码_如何在软件开发的迷宫中找到自己的出路
迷宫出路代码by Tim Kleier蒂姆克莱尔(Tim Kleier) 如何在软件开发的迷宫中找到自己的出路 (How to find your way through the corn maze of software development) The corn maze is one of my favorite challenges to tackle. It’s an unnerving experience, especially w…

打包 React 项目并在服务器运行。
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 1.找到项目根目录的package.json文件:如图: 2.打开cmd执行:npm run build 3.生成DIST文件夹。 4.把DIST文件放到服务器phpStudty根目录,访问index.html。…

一些有用的Python问题
1. 修改IDLE工作路径,在命令交互模式下输入如下指令: >>> import os >>> os.getcwd() #查看当前的工作路径 >>> os.chdir(E:\\Python\\Demo) #修改当前的工作路径 2.Python中 ImportError: cannot import name NUMPY_MKL 的…

Python核心编程笔记---- print
在仅用变量名时,输出的字符串是用单引号括起来的。这个是为了让非字符串对象也可能以字符的形式显示在屏幕上。 而print 函数打印出来的是变量的值。 print 调用的是str()方法。而仅用变量名时调用的是repr()方法。 证明:------------------------------…

latex 插图解释_大O符号-只需插图和视频即可解释
latex 插图解释Big O notation is used to communicate how fast an algorithm is. This can be important when evaluating other people’s algorithms, and when evaluating your own! In this article, I’ll explain what Big O notation is and give you a list of the m…

[YTU]_2002(C语言实验——单词统计)
Description 从键盘输入一行字符,统计其中单词的个数,各单词以空格分隔,且空格数可以是多个。Input 输入只有一行句子。仅有空格和英文字母构成。 Output 单词的个数。 Sample Input stable marriage problem Consists of Matching memb…

资本中国人物-金融
一、二、三、店、五、土地、七、八、玖、拾起、白、千、一万、一亿、元(圆)、角、支、零、整个。这是上图中我们经常要填写。问:什么是它用数词?想必很多人都不是很清楚! 请看下面的两个相关的表数词: 1、数字化和大、小写数字对照…

Ant Design Pro 网络请求流程
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 在 Ant Design Pro 中,一个完整的前端 UI 交互到服务端处理流程是这样的: UI 组件交互操作; 调用 model 的 effect; 调用统一管理的 service 请求函数&a…

在Google Cloud Platform上持续部署Node.js
by Gautam Arora由Gautam Arora 在Google Cloud Platform上持续部署Node.js (Continuous Deployment for Node.js on the Google Cloud Platform) Google Cloud Platform (GCP) provides a host of options for Node developers to easily deploy our apps. Want a managed ho…

hdu-1108 最小公倍数
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid1108 题目类型: 数论 题意概括: 求两个数的最小公倍数 解题思路: 模拟 题目: 最小公倍数 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/O…

sql-schema与catalog
schema: 指的是说当偶create database caiceclb时,caiceclb就是一个schema catalog: 指的是所有的database目录,就像上图显示的那样,将MySQL原来的(mysql,infomation_schema)及后来新建的的data…

这是如何更好地利用JavaScript数组的方法
by pacdiv由pacdiv 这是如何更好地利用JavaScript数组的方法 (Here’s how you can make better use of JavaScript arrays) Quick read, I promise. Over the last few months, I noticed that the exact same four mistakes kept coming back through the pull requests I c…