10 |
11 | # 深入 '...' 各种情况下的表现形式
12 | 在js中,合并多个对象是一种很常见的操作,在ES5的时候,没有一种很方便的语法来进行对象的合并。在ES6中引入了一个对象函数Object.assgin(source, [target]),再之后又引入了**对象的spread语法**。
13 |
14 |
15 |
16 | 如下:
17 | ```javascript
18 | const cat = {
19 | legs: 4,
20 | sound: 'meow',
21 | };
22 | const dog = {
23 | ...cat,
24 | sound: 'woof'
25 | };
26 |
27 | /* 最后结果
28 | dog => {
29 | legs: 4,
30 | sound: 'woof',
31 | }
32 | */
33 | ```
34 |
35 | ## spread与属性的可枚举配置
36 | 在ES5及之后的规范中,对象的每一个属性都存在几个来描述该属性的属性。这些值用来描述对象的属性是否可写、可枚举和可配置的状态。这里只说可枚举属性,可枚举属性是一个bool值,代表对象属性是否可以被访问。我们可以使用`Object.keys()`来访问**自己的和可枚举属性**,也可以使用`for...in`语句来**遍历所有可枚举的属性**
37 | 如下:
38 | ```javascript
39 | const person = {
40 | name: 'zachrey',
41 | age: 21,
42 | };
43 | Object.keys(person); // ['name', 'age']
44 | console.log({...person});
45 | /*
46 | {
47 | name: 'zachrey',
48 | age: 21,
49 | }
50 | */
51 | ```
52 | 所以`name` `age`是`person`对象中的可枚举属性,目前来说spread可以克隆所有的可枚举属性。
53 | 现在我们来给`person`定义一个不可以枚举的属性,再使用spread看能不能克隆出来。
54 | ```javascript
55 | Object.defineProperty(person, 'sex', {
56 | enumerable: false,
57 | value: 'male',
58 | });
59 | console.log(person['sex']);// male
60 |
61 | const clonePerson = {
62 | ...person,
63 | };
64 | console.log(Object.keys(person));// ['name', 'age']
65 | console.log(clonePerson);
66 | /*
67 | {
68 | name: 'zachrey',
69 | age: 21,
70 | }
71 | */
72 | ```
73 | 通过以上可以看出来:
74 | 1. 不可枚举属性,可以被访问,使用`console.log`打印出来。
75 | 2. `...`**并不能克隆**不可枚举属性。
76 | 3. `...`的表现形式与`Object.keys`的表现形式相同。
77 |
78 | ## spread与自身属性
79 | 对于一个js对象,它的属性可以是自己的也可能是原型链上的,接下来简单的实现以下继承。
80 | ```javascript
81 | const personB = Object.create(person, {
82 | profession: {
83 | value: 'development',
84 | enumerable: true,
85 | }
86 | });
87 | console.log(personB.hasOwnProperty('profession')); // => true
88 | console.log(personB.hasOwnProperty('name')); // => false
89 | console.log(personB.hasOwnProperty('age')); // => false
90 | ```
91 | 如上,只有`profession`是属于`personB`自身的。
92 | **Object spread从自己的源属性中进行复制的时候,会忽略继承的属性。**
93 | 如下:
94 | ```javascript
95 | const cloneB = { ...personB };
96 | console.log(cloneB); // => { profession: 'development' }
97 | ```
98 | > Object spread可以从源对象中复制自己的和可枚举的属性。和Object.keys()相同。
99 |
100 | ## Object spread规则:最后属性获胜
101 | *** 后者扩展属性覆盖具有相同键的早期属性 ***
102 | 如下:
103 | ```javascript
104 | const cat = {
105 | sound: 'meow',
106 | legs: 4,
107 | };
108 |
109 | const dog = {
110 | ...cat,
111 | ...{
112 | sound: 'woof' // <----- 覆盖 cat.sound
113 | }
114 | };
115 | console.log(dog); // => { sound: 'woof', legs: 4 }
116 |
117 | const anotherDog = {
118 | ...cat,
119 | sound: 'woof' // <---- Overwrites cat.sound
120 | };
121 | console.log(anotherDog); // => { sound: 'woof', legs: 4 }
122 | ```
123 | ## 浅拷贝
124 | spread对值是复合类型的属性,只会拷贝它对该值得应用。
125 | 如下:
126 | ```javascript
127 |
128 | const laptop = {
129 | name: 'MacBook Pro',
130 | screen: { size: 17, isRetina: true }
131 | };
132 | const laptopClone = { ...laptop };
133 | console.log(laptop === laptopClone); // => false
134 | console.log(laptop.screen === laptopClone.screen); // => true
135 | ```
136 | 首先比较`laptop === laptopClone`,其值是false。主对象被正确克隆。
137 |
138 | 然而,`laptop.screen === laptopClone.screen`值是true。这意味着,`laptop.screen`和`laptopClone.screen`引用相同的嵌套对象,但没有复制。
139 |
140 | ## 原型丢失
141 |
142 | 这里先声明一个类:
143 | ```javascript
144 | class Game {
145 | constructor(name) {
146 | this.name = name;
147 | }
148 | getMessage() {
149 | return `I like ${this.name}!`;
150 | }
151 | }
152 | const doom = new Game('Doom');
153 | console.log(doom instanceof Game); // => true console.log(doom.name); // => "Doom"
154 | console.log(doom.getMessage()); // => "I like Doom!"
155 | ```
156 | 接下来我们使用spread克隆调用构造函数创建的`doom`实例:
157 | ```javascript
158 | const doomClone = { ...doom };
159 | console.log(doomClone instanceof Game); // => false
160 | console.log(doomClone.name); // => "Doom"
161 | console.log(doomClone.getMessage()); // => TypeError: doomClone.getMessage is not a function
162 | ```
163 | `...doom`只将自己的属性name复制到`doomClone`而已。doomClone是一个普通的JavaScript对象,其原型是`Object.prototype`,而不是`Game.prototype`,这是可以预期的。Object Spread**不保存源对象的原型**。
164 | 想要修复原型可以使用`Object.setPrototypeOf(doomClone, Game.prototype)`。
165 | 使用Object.assign()可以更合理的克隆doom:
166 | ```javascript
167 | const doomFullClone = Object.assign(new Game(), doom);
168 | console.log(doomFullClone instanceof Game); // => true
169 | console.log(doomFullClone.name); // => "Doom"
170 | console.log(doomFullClone.getMessage()); // => "I like Doom!"
171 | ```
172 |
173 | ## 传播undefined、null和基本类型
174 | ```javascript
175 | const nothing = undefined;
176 | const missingObject = null;
177 | const two = 2;
178 | console.log({ ...nothing }); // => { }
179 | console.log({ ...missingObject }); // => { }
180 | console.log({ ...two }); // => { }
181 | ```
182 |
183 | ## 总结
184 |
185 | Object spread有一些规则要记住:
186 |
187 | * 它从源对象中提取自己的和可枚举的属性
188 | * 扩展的属性具有相同键的,后者会覆盖前者
189 |
190 | 与此同时,Object spread是简短而且富有表现力的,同时在嵌套对象上也能很好的工作,同时也保持更新的不变性。它可以轻松的实现对象克隆、合并和填充默认属性。
191 |
192 | 在结构性赋值中使用Object rest语法,可以收集剩余的属性。
193 |
194 | 实际上,Object rest和Object spread是JavaScript的重要补充。
195 |
196 | >[原文链接](https://www.w3cplus.com/javascript/how-three-dots-changed-javascript-object-rest-spread-properties.html "原文链接")
197 |
198 | 
--------------------------------------------------------------------------------
/cmd/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "fmt"
7 | "io"
8 | "io/ioutil"
9 | "log"
10 | "mime/multipart"
11 | "net/http"
12 | "os"
13 | "path/filepath"
14 |
15 | "github.com/urfave/cli"
16 | )
17 |
18 | func main() {
19 | app := cli.NewApp()
20 | app.Name = "bpost"
21 | app.Usage = "Managing blog posts"
22 | app.Version = "0.0.1"
23 |
24 | var filePath string
25 | var fileName string
26 | var host string
27 |
28 | app.Flags = []cli.Flag{
29 | cli.StringFlag{
30 | Name: "upload,up",
31 | Usage: "Upload an article by that `file path`",
32 | Destination: &filePath,
33 | },
34 | cli.StringFlag{
35 | Name: "remove,rm",
36 | Usage: "Remove the article by that `file name`",
37 | Destination: &fileName,
38 | },
39 | cli.StringFlag{
40 | Name: "config,cf",
41 | Usage: "Config http request `host`",
42 | Destination: &host,
43 | },
44 | }
45 | var url = "http://localhost:8888"
46 | isexists := exists("./url.config")
47 | if isexists {
48 | file, rdRrr := ioutil.ReadFile("./url.config")
49 | if rdRrr != nil {
50 | log.Fatalln("[ERROR] ", rdRrr)
51 | }
52 | url = string(file)
53 | }
54 |
55 | app.Action = func(c *cli.Context) error {
56 | if filePath != "" {
57 | upload(filePath, url)
58 | }
59 | if fileName != "" {
60 | remove(fileName, url)
61 | }
62 | if host != "" {
63 | config(host)
64 | }
65 | return nil
66 | }
67 | err := app.Run(os.Args)
68 | checkErr(err)
69 | }
70 |
71 | func upload(filePath, url string) {
72 | _, err := os.Stat(filePath) //os.Stat获取文件信息
73 | if err != nil {
74 | if os.IsExist(err) == false {
75 | log.Fatalf("%s 路径不存在", filePath)
76 | }
77 | }
78 | // 创建表单文件
79 | // CreateFormFile 用来创建表单,第一个参数是字段名,第二个参数是文件名
80 | buf := new(bytes.Buffer)
81 | writer := multipart.NewWriter(buf)
82 | fileName := filepath.Base(filePath)
83 | formFile, err := writer.CreateFormFile("upload", fileName)
84 | if err != nil {
85 | log.Fatalf("Create form file failed: %s\n", err)
86 | }
87 |
88 | // 从文件读取数据,写入表单
89 | srcFile, err := os.Open(filePath)
90 | if err != nil {
91 | log.Fatalf("Open source file failed: %s\n", err)
92 | }
93 | defer srcFile.Close()
94 | _, err = io.Copy(formFile, srcFile)
95 | if err != nil {
96 | log.Fatalf("Write to form file falied: %s\n", err)
97 | }
98 |
99 | // 发送表单
100 | contentType := writer.FormDataContentType()
101 | writer.Close() // 发送之前必须调用Close()以写入结尾行
102 | var res *http.Response
103 | res, err = http.Post(url+"/upload", contentType, buf)
104 | if err != nil {
105 | log.Fatalf("Post failed: %s\n", err)
106 | }
107 | defer res.Body.Close()
108 | body, _ := ioutil.ReadAll(res.Body)
109 | var dataMap map[string]interface{}
110 | json.Unmarshal(body, &dataMap)
111 | if dataMap["status"] != 0 {
112 | log.Fatalf("Post failed: %s\n", dataMap["msg"])
113 | }
114 | log.Println("[SUCCESS] Upload file is successfully. ", filePath)
115 | }
116 |
117 | func remove(fileName, url string) {
118 | res, err := http.Get(url + "/remove?name=" + fileName)
119 | if err != nil {
120 | log.Fatalf("Remove failed: %s\n", err)
121 | }
122 | defer res.Body.Close()
123 | body, _ := ioutil.ReadAll(res.Body)
124 | var dataMap map[string]interface{}
125 | json.Unmarshal(body, &dataMap)
126 | if dataMap["status"] != 0 {
127 | log.Fatalf("Post failed: %s\n", dataMap["msg"])
128 | }
129 | fmt.Println("[SUCCESS] Remove file is successfully. ", fileName)
130 | }
131 |
132 | func config(host string) {
133 | var file *os.File
134 | var err error
135 | file, err = os.OpenFile("./url.config", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, os.ModePerm)
136 | defer file.Close()
137 |
138 | if err != nil {
139 | log.Fatalln("[ERROR] ", err)
140 | }
141 |
142 | _, err = file.WriteString(host)
143 | if err != nil {
144 | log.Fatalln("[ERROR] ", err)
145 | } else {
146 | log.Fatalln("[SUCCESSFUL] 配置成功!")
147 | }
148 | }
149 |
150 | func checkErr(e error) {
151 | if e != nil {
152 | log.Fatalln("ERROR:", e)
153 | }
154 | }
155 |
156 | func exists(path string) bool {
157 | _, err := os.Stat(path) //os.Stat获取文件信息
158 | if err != nil {
159 | if os.IsExist(err) {
160 | return true
161 | }
162 | return false
163 | }
164 | return true
165 | }
166 |
--------------------------------------------------------------------------------
/cmd/test.md:
--------------------------------------------------------------------------------
1 | title: 一个博客的名称
2 | categories: 分类1, 分类2, 分类3
3 | label: 标签1, 标签2
4 | ---------------------------------------------
5 |
6 | # 标题
7 | **it's golang**
8 |
--------------------------------------------------------------------------------
/cmd/url.config:
--------------------------------------------------------------------------------
1 | http://localhost:8888
--------------------------------------------------------------------------------
/controllers/category.go:
--------------------------------------------------------------------------------
1 | package controllers
2 |
3 | import (
4 | "net/http"
5 |
6 | "github.com/gin-gonic/gin"
7 | "github.com/zachrey/blog/models"
8 | )
9 |
10 | //GetLabels 获取所有的标签
11 | func GetCategoies(c *gin.Context) {
12 | labels := models.GetCategories()
13 | c.JSON(http.StatusOK, gin.H{
14 | "status": 0,
15 | "data": labels,
16 | })
17 | }
18 |
--------------------------------------------------------------------------------
/controllers/label.go:
--------------------------------------------------------------------------------
1 | package controllers
2 |
3 | import (
4 | "net/http"
5 |
6 | "github.com/gin-gonic/gin"
7 | "github.com/zachrey/blog/models"
8 | )
9 |
10 | //GetLabels 获取所有的标签
11 | func GetLabels(c *gin.Context) {
12 | labels := models.GetLabels()
13 | c.JSON(http.StatusOK, gin.H{
14 | "status": 0,
15 | "data": labels,
16 | })
17 | }
18 |
--------------------------------------------------------------------------------
/controllers/md2html.go:
--------------------------------------------------------------------------------
1 | package controllers
2 |
3 | import (
4 | "io/ioutil"
5 | "log"
6 | "net/http"
7 | "strconv"
8 | "strings"
9 |
10 | "github.com/gin-gonic/gin"
11 | "github.com/russross/blackfriday"
12 | "github.com/zachrey/blog/models"
13 | )
14 |
15 | // GetHtmlStr 根据params获取id,读取本地md文件,然后返回字符串
16 | func GetHtmlStr(c *gin.Context) {
17 | postid := c.Param("postid")
18 | if postid == "" {
19 | c.JSON(http.StatusNotFound, gin.H{
20 | "status": 1,
21 | "msg": "postid 不能为空",
22 | })
23 | }
24 | postID, err := strconv.ParseInt(postid, 10, 64)
25 | if err != nil {
26 | log.Println(err)
27 | c.JSON(http.StatusNotFound, gin.H{
28 | "status": 1,
29 | "msg": "postid can't convert to int64, the error information: " + err.Error(),
30 | })
31 | }
32 |
33 | postInfo := models.GetPostByID(postID)
34 | file, openErr := ioutil.ReadFile("./posts/" + postInfo.FileName)
35 | if openErr != nil {
36 | log.Println(err)
37 | c.JSON(http.StatusNotFound, gin.H{
38 | "status": 1,
39 | "msg": err.Error(),
40 | })
41 | }
42 |
43 | lines := strings.Split(string(file), "\n")
44 | body := strings.Join(lines[5:], "\n")
45 | body = string(blackfriday.MarkdownCommon([]byte(body)))
46 | c.JSON(http.StatusOK, gin.H{
47 | "status": 0,
48 | "data": body,
49 | })
50 | }
51 |
--------------------------------------------------------------------------------
/controllers/posts.go:
--------------------------------------------------------------------------------
1 | package controllers
2 |
3 | import (
4 | "log"
5 | "net/http"
6 | "strconv"
7 |
8 | "github.com/gin-gonic/gin"
9 | "github.com/zachrey/blog/models"
10 | )
11 |
12 | //GetPosts 获取所有的文章
13 | func GetPosts(c *gin.Context) {
14 | labels := models.GetPosts()
15 | c.JSON(http.StatusOK, gin.H{
16 | "status": 0,
17 | "data": labels,
18 | })
19 | }
20 |
21 | //GetPostByLabelId 根据label id获取post
22 | func GetPostByLabelId(c *gin.Context) {
23 | labelid := c.Param("labelid")
24 | if labelid == "" {
25 | c.JSON(http.StatusNotFound, gin.H{
26 | "status": 1,
27 | "msg": "labelid 不能为空",
28 | })
29 | }
30 | labelId, err := strconv.ParseInt(labelid, 10, 64)
31 | posts := models.GetPostsByPLId(labelId)
32 | if err != nil {
33 | log.Println(err)
34 | c.JSON(http.StatusNotFound, gin.H{
35 | "status": 1,
36 | "msg": "labelid can't convert to int64, the error information: " + err.Error(),
37 | })
38 | }
39 | c.JSON(http.StatusOK, gin.H{
40 | "status": 0,
41 | "data": posts,
42 | })
43 | }
44 |
45 | //GetPostByCategoryId category id获取post
46 | func GetPostByCategoryId(c *gin.Context) {
47 | categoryid := c.Param("categoryid")
48 | if categoryid == "" {
49 | c.JSON(http.StatusNotFound, gin.H{
50 | "status": 1,
51 | "msg": "categoryid 不能为空",
52 | })
53 | }
54 | categoryId, err := strconv.ParseInt(categoryid, 10, 64)
55 | posts := models.GetPostsByPCId(categoryId)
56 | if err != nil {
57 | log.Println(err)
58 | c.JSON(http.StatusNotFound, gin.H{
59 | "status": 1,
60 | "msg": "categoryid can't convert to int64, the error information: " + err.Error(),
61 | })
62 | }
63 | c.JSON(http.StatusOK, gin.H{
64 | "status": 0,
65 | "data": posts,
66 | })
67 | }
68 |
--------------------------------------------------------------------------------
/controllers/removeFile.go:
--------------------------------------------------------------------------------
1 | package controllers
2 |
3 | import (
4 | "log"
5 | "net/http"
6 | "os"
7 | "sync"
8 |
9 | "github.com/gin-gonic/gin"
10 | "github.com/zachrey/blog/models"
11 | )
12 |
13 | var wg sync.WaitGroup
14 |
15 | // RemoveFile 根据标题删除文章及相关项
16 | func RemoveFile(c *gin.Context) {
17 | wg.Add(3)
18 | fileName := c.Query("name")
19 | if fileName == "" {
20 | c.JSON(http.StatusOK, gin.H{
21 | "status": 1,
22 | "msg": "Filed name is empty.",
23 | })
24 | return
25 | }
26 |
27 | post := models.GetPostByTitle(fileName)
28 |
29 | // 删除分类关联表
30 | go func() {
31 | models.RemovePCByPostID(post.Id)
32 | wg.Done()
33 | }()
34 | // 删除标签关联表
35 | go func() {
36 | models.RemovePLByPostID(post.Id)
37 | wg.Done()
38 | }()
39 | // 删除文件
40 | go func() {
41 | err := os.Remove("./posts/" + post.FileName)
42 | if err != nil {
43 | log.Println("[ERROR] ", err)
44 | }
45 | wg.Done()
46 | }()
47 | wg.Wait()
48 | models.RemovePostByID(post.Id)
49 |
50 | c.JSON(http.StatusOK, gin.H{
51 | "status": 0,
52 | "msg": "删除文章成功!",
53 | })
54 | }
55 |
--------------------------------------------------------------------------------
/controllers/uploadfile.go:
--------------------------------------------------------------------------------
1 | package controllers
2 |
3 | import (
4 | "crypto/md5"
5 | "errors"
6 | "fmt"
7 | "io"
8 | "io/ioutil"
9 | "log"
10 | "math"
11 | "net/http"
12 | "os"
13 | "path/filepath"
14 | "regexp"
15 | "strings"
16 | "sync"
17 | "unicode"
18 |
19 | "github.com/gin-gonic/gin"
20 | "github.com/zachrey/blog/models"
21 | )
22 |
23 | const postDir = "./posts/"
24 |
25 | var gr sync.WaitGroup
26 | var isShouldRemove = false
27 |
28 | // UpLoadFile 上传文件的控制器
29 | func UpLoadFile(c *gin.Context) {
30 | file, header, err := c.Request.FormFile("upload")
31 | filename := header.Filename
32 | md5FileName := fmt.Sprintf("%x", md5.Sum([]byte(filename)))
33 | fileExt := filepath.Ext(postDir + filename)
34 | filePath := postDir + md5FileName + fileExt
35 | log.Println("[INFO] upload file: ", header.Filename)
36 |
37 | has := hasSameNameFile(md5FileName+fileExt, postDir)
38 | if has {
39 | c.JSON(http.StatusOK, gin.H{
40 | "status": 1,
41 | "msg": "服务器已有相同文件名称",
42 | })
43 | return
44 | }
45 |
46 | // 根据文件名的md5值,创建服务器上的文件
47 | out, err := os.Create(filePath)
48 | if err != nil {
49 | log.Fatal(err)
50 | }
51 |
52 | // 处理完整个上传过程后,是否需要删除创建的文件,在存在错误的情况下
53 | defer func() {
54 | if isShouldRemove {
55 | err = os.Remove(filePath)
56 | if err != nil {
57 | log.Println("[ERROR] ", err)
58 | }
59 | }
60 | }()
61 | defer out.Close()
62 |
63 | _, err = io.Copy(out, file)
64 | if err != nil {
65 | log.Fatal(err)
66 | }
67 |
68 | err = readMdFileInfo(filePath)
69 | if err != nil {
70 | isShouldRemove = true
71 | c.JSON(http.StatusOK, gin.H{
72 | "status": 1,
73 | "msg": err.Error(),
74 | })
75 | return
76 | }
77 |
78 | c.JSON(http.StatusOK, gin.H{
79 | "status": 0,
80 | "msg": "上传成功",
81 | })
82 | }
83 |
84 | func readMdFileInfo(filePath string) error {
85 | fileread, _ := ioutil.ReadFile(filePath)
86 | lines := strings.Split(string(fileread), "\n")
87 | body := strings.Join(lines[5:], "")
88 | textAmount := GetStrLength(body)
89 | log.Println(lines)
90 | const (
91 | TITLE = "title: "
92 | CATEGORIES = "categories: "
93 | LABEL = "label: "
94 | )
95 | var (
96 | postId int64
97 | postCh chan int64
98 | categoryCh chan []int64
99 | labelCh chan []int64
100 | )
101 | mdInfo := make(map[string]string)
102 |
103 | for i, lens := 0, len(lines); i < lens && i < 5; i++ { // 只查找前五行
104 | switch {
105 | case strings.HasPrefix(lines[i], TITLE):
106 | mdInfo[TITLE] = strings.TrimLeft(lines[i], TITLE)
107 | postCh = make(chan int64)
108 | go models.InsertPost(mdInfo[TITLE], filepath.Base(filePath), int64(textAmount), postCh)
109 | case strings.HasPrefix(lines[i], CATEGORIES):
110 | mdInfo[CATEGORIES] = strings.TrimLeft(lines[i], CATEGORIES)
111 | categoryCh = make(chan []int64)
112 | go models.InsertCategory(mdInfo[CATEGORIES], categoryCh)
113 | case strings.HasPrefix(lines[i], LABEL):
114 | mdInfo[LABEL] = strings.TrimLeft(lines[i], LABEL)
115 | labelCh = make(chan []int64)
116 | go models.InsertLabel(mdInfo[LABEL], labelCh)
117 | }
118 | }
119 | postId = <-postCh
120 | if postId == 0 {
121 | return errors.New("服务器上已有相同文章标题")
122 | }
123 | log.Println("[INFO] postId: ", postId)
124 | if categoryCh != nil {
125 | go func() {
126 | categoryIds := <-categoryCh
127 | log.Println("[INFO] categoryIds: ", categoryIds)
128 |
129 | for _, v := range categoryIds {
130 | models.InsertPostAndCategory(postId, v)
131 | }
132 | }()
133 | }
134 |
135 | if labelCh != nil {
136 | go func() {
137 | labels := <-labelCh
138 | log.Println("[INFO] labels: ", labels)
139 |
140 | for _, v := range labels {
141 | models.InsertPostAndLabel(postId, v)
142 | }
143 | }()
144 | }
145 | return nil
146 | // 接下来就是将各种信息存入数据库
147 | }
148 |
149 | func hasSameNameFile(fileName, dir string) bool {
150 | files, _ := ioutil.ReadDir(dir)
151 | for _, f := range files {
152 | if fileName == f.Name() {
153 | return true
154 | }
155 | }
156 | return false
157 | }
158 |
159 | // GetStrLength 返回输入的字符串的字数,汉字和中文标点算 1 个字数,英文和其他字符 2 个算 1 个字数,不足 1 个算 1个
160 | func GetStrLength(str string) float64 {
161 | var total float64
162 |
163 | reg := regexp.MustCompile("/·|,|。|《|》|‘|’|”|“|;|:|【|】|?|(|)|、/")
164 |
165 | for _, r := range str {
166 | if unicode.Is(unicode.Scripts["Han"], r) || reg.Match([]byte(string(r))) {
167 | total = total + 1
168 | } else {
169 | total = total + 0.5
170 | }
171 | }
172 |
173 | return math.Ceil(total)
174 | }
175 |
--------------------------------------------------------------------------------
/database/sqlite3.go:
--------------------------------------------------------------------------------
1 | package database
2 |
3 | import (
4 | "log"
5 |
6 | "github.com/xormplus/xorm"
7 | )
8 |
9 | // ORM xorm引擎的实例
10 | var ORM *xorm.Engine
11 |
12 | func init() {
13 | var err error
14 | ORM, err = xorm.NewEngine("sqlite3", "./database/test.db")
15 | if err != nil {
16 | log.Fatalln(err)
17 | return
18 | }
19 | err = ORM.Ping()
20 | if err != nil {
21 | log.Fatalln(err)
22 | return
23 | }
24 | ORM.ShowSQL(true)
25 | }
26 |
--------------------------------------------------------------------------------
/database/test.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bruce-16/my-blog-by-go/38d3e5491d079394a9ce066127c917fe8010ba74/database/test.db
--------------------------------------------------------------------------------
/debug:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bruce-16/my-blog-by-go/38d3e5491d079394a9ce066127c917fe8010ba74/debug
--------------------------------------------------------------------------------
/front_web/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 |
6 | # testing
7 | /coverage
8 |
9 | # production
10 | /build
11 |
12 | # misc
13 | .DS_Store
14 | .env.local
15 | .env.development.local
16 | .env.test.local
17 | .env.production.local
18 |
19 | npm-debug.log*
20 | yarn-debug.log*
21 | yarn-error.log*
22 |
--------------------------------------------------------------------------------
/front_web/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
2 |
3 | Below you will find some information on how to perform common tasks.
4 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md).
5 |
6 | ## Table of Contents
7 |
8 | - [Updating to New Releases](#updating-to-new-releases)
9 | - [Sending Feedback](#sending-feedback)
10 | - [Folder Structure](#folder-structure)
11 | - [Available Scripts](#available-scripts)
12 | - [npm start](#npm-start)
13 | - [npm test](#npm-test)
14 | - [npm run build](#npm-run-build)
15 | - [npm run eject](#npm-run-eject)
16 | - [Supported Browsers](#supported-browsers)
17 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills)
18 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
19 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
20 | - [Debugging in the Editor](#debugging-in-the-editor)
21 | - [Formatting Code Automatically](#formatting-code-automatically)
22 | - [Changing the Page ``](#changing-the-page-title)
23 | - [Installing a Dependency](#installing-a-dependency)
24 | - [Importing a Component](#importing-a-component)
25 | - [Code Splitting](#code-splitting)
26 | - [Adding a Stylesheet](#adding-a-stylesheet)
27 | - [Post-Processing CSS](#post-processing-css)
28 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
29 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files)
30 | - [Using the `public` Folder](#using-the-public-folder)
31 | - [Changing the HTML](#changing-the-html)
32 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
33 | - [When to Use the `public` Folder](#when-to-use-the-public-folder)
34 | - [Using Global Variables](#using-global-variables)
35 | - [Adding Bootstrap](#adding-bootstrap)
36 | - [Using a Custom Theme](#using-a-custom-theme)
37 | - [Adding Flow](#adding-flow)
38 | - [Adding a Router](#adding-a-router)
39 | - [Adding Custom Environment Variables](#adding-custom-environment-variables)
40 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
41 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
42 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
43 | - [Can I Use Decorators?](#can-i-use-decorators)
44 | - [Fetching Data with AJAX Requests](#fetching-data-with-ajax-requests)
45 | - [Integrating with an API Backend](#integrating-with-an-api-backend)
46 | - [Node](#node)
47 | - [Ruby on Rails](#ruby-on-rails)
48 | - [Proxying API Requests in Development](#proxying-api-requests-in-development)
49 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy)
50 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually)
51 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy)
52 | - [Using HTTPS in Development](#using-https-in-development)
53 | - [Generating Dynamic `` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
54 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
55 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
56 | - [Running Tests](#running-tests)
57 | - [Filename Conventions](#filename-conventions)
58 | - [Command Line Interface](#command-line-interface)
59 | - [Version Control Integration](#version-control-integration)
60 | - [Writing Tests](#writing-tests)
61 | - [Testing Components](#testing-components)
62 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
63 | - [Initializing Test Environment](#initializing-test-environment)
64 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests)
65 | - [Coverage Reporting](#coverage-reporting)
66 | - [Continuous Integration](#continuous-integration)
67 | - [Disabling jsdom](#disabling-jsdom)
68 | - [Snapshot Testing](#snapshot-testing)
69 | - [Editor Integration](#editor-integration)
70 | - [Debugging Tests](#debugging-tests)
71 | - [Debugging Tests in Chrome](#debugging-tests-in-chrome)
72 | - [Debugging Tests in Visual Studio Code](#debugging-tests-in-visual-studio-code)
73 | - [Developing Components in Isolation](#developing-components-in-isolation)
74 | - [Getting Started with Storybook](#getting-started-with-storybook)
75 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist)
76 | - [Publishing Components to npm](#publishing-components-to-npm)
77 | - [Making a Progressive Web App](#making-a-progressive-web-app)
78 | - [Opting Out of Caching](#opting-out-of-caching)
79 | - [Offline-First Considerations](#offline-first-considerations)
80 | - [Progressive Web App Metadata](#progressive-web-app-metadata)
81 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size)
82 | - [Deployment](#deployment)
83 | - [Static Server](#static-server)
84 | - [Other Solutions](#other-solutions)
85 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
86 | - [Building for Relative Paths](#building-for-relative-paths)
87 | - [Azure](#azure)
88 | - [Firebase](#firebase)
89 | - [GitHub Pages](#github-pages)
90 | - [Heroku](#heroku)
91 | - [Netlify](#netlify)
92 | - [Now](#now)
93 | - [S3 and CloudFront](#s3-and-cloudfront)
94 | - [Surge](#surge)
95 | - [Advanced Configuration](#advanced-configuration)
96 | - [Troubleshooting](#troubleshooting)
97 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes)
98 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
99 | - [`npm run build` exits too early](#npm-run-build-exits-too-early)
100 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
101 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify)
102 | - [Moment.js locales are missing](#momentjs-locales-are-missing)
103 | - [Alternatives to Ejecting](#alternatives-to-ejecting)
104 | - [Something Missing?](#something-missing)
105 |
106 | ## Updating to New Releases
107 |
108 | Create React App is divided into two packages:
109 |
110 | * `create-react-app` is a global command-line utility that you use to create new projects.
111 | * `react-scripts` is a development dependency in the generated projects (including this one).
112 |
113 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
114 |
115 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically.
116 |
117 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions.
118 |
119 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes.
120 |
121 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly.
122 |
123 | ## Sending Feedback
124 |
125 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues).
126 |
127 | ## Folder Structure
128 |
129 | After creation, your project should look like this:
130 |
131 | ```
132 | my-app/
133 | README.md
134 | node_modules/
135 | package.json
136 | public/
137 | index.html
138 | favicon.ico
139 | src/
140 | App.css
141 | App.js
142 | App.test.js
143 | index.css
144 | index.js
145 | logo.svg
146 | ```
147 |
148 | For the project to build, **these files must exist with exact filenames**:
149 |
150 | * `public/index.html` is the page template;
151 | * `src/index.js` is the JavaScript entry point.
152 |
153 | You can delete or rename the other files.
154 |
155 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.
156 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them.
157 |
158 | Only files inside `public` can be used from `public/index.html`.
159 | Read instructions below for using assets from JavaScript and HTML.
160 |
161 | You can, however, create more top-level directories.
162 | They will not be included in the production build so you can use them for things like documentation.
163 |
164 | ## Available Scripts
165 |
166 | In the project directory, you can run:
167 |
168 | ### `npm start`
169 |
170 | Runs the app in the development mode.
171 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
172 |
173 | The page will reload if you make edits.
174 | You will also see any lint errors in the console.
175 |
176 | ### `npm test`
177 |
178 | Launches the test runner in the interactive watch mode.
179 | See the section about [running tests](#running-tests) for more information.
180 |
181 | ### `npm run build`
182 |
183 | Builds the app for production to the `build` folder.
184 | It correctly bundles React in production mode and optimizes the build for the best performance.
185 |
186 | The build is minified and the filenames include the hashes.
187 | Your app is ready to be deployed!
188 |
189 | See the section about [deployment](#deployment) for more information.
190 |
191 | ### `npm run eject`
192 |
193 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
194 |
195 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
196 |
197 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
198 |
199 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
200 |
201 | ## Supported Browsers
202 |
203 | By default, the generated project uses the latest version of React.
204 |
205 | You can refer [to the React documentation](https://reactjs.org/docs/react-dom.html#browser-support) for more information about supported browsers.
206 |
207 | ## Supported Language Features and Polyfills
208 |
209 | This project supports a superset of the latest JavaScript standard.
210 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:
211 |
212 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
213 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
214 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal).
215 | * [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal)
216 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal).
217 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax.
218 |
219 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-).
220 |
221 | While we recommend using experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future.
222 |
223 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**:
224 |
225 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign).
226 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise).
227 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch).
228 |
229 | If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them.
230 |
231 | Also note that using some newer syntax features like `for...of` or `[...nonArrayValue]` causes Babel to emit code that depends on ES6 runtime features and might not work without a polyfill. When in doubt, use [Babel REPL](https://babeljs.io/repl/) to see what any specific syntax compiles down to.
232 |
233 | ## Syntax Highlighting in the Editor
234 |
235 | To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered.
236 |
237 | ## Displaying Lint Output in the Editor
238 |
239 | >Note: this feature is available with `react-scripts@0.2.0` and higher.
240 | >It also only works with npm 3 or higher.
241 |
242 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
243 |
244 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do.
245 |
246 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root:
247 |
248 | ```js
249 | {
250 | "extends": "react-app"
251 | }
252 | ```
253 |
254 | Now your editor should report the linting warnings.
255 |
256 | Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes.
257 |
258 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules.
259 |
260 | ## Debugging in the Editor
261 |
262 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).**
263 |
264 | Visual Studio Code and WebStorm support debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools.
265 |
266 | ### Visual Studio Code
267 |
268 | You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed.
269 |
270 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory.
271 |
272 | ```json
273 | {
274 | "version": "0.2.0",
275 | "configurations": [{
276 | "name": "Chrome",
277 | "type": "chrome",
278 | "request": "launch",
279 | "url": "http://localhost:3000",
280 | "webRoot": "${workspaceRoot}/src",
281 | "sourceMapPathOverrides": {
282 | "webpack:///src/*": "${webRoot}/*"
283 | }
284 | }]
285 | }
286 | ```
287 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
288 |
289 | Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor.
290 |
291 | Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting).
292 |
293 | ### WebStorm
294 |
295 | You would need to have [WebStorm](https://www.jetbrains.com/webstorm/) and [JetBrains IDE Support](https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji) Chrome extension installed.
296 |
297 | In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `JavaScript Debug`. Paste `http://localhost:3000` into the URL field and save the configuration.
298 |
299 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
300 |
301 | Start your app by running `npm start`, then press `^D` on macOS or `F9` on Windows and Linux or click the green debug icon to start debugging in WebStorm.
302 |
303 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine.
304 |
305 | ## Formatting Code Automatically
306 |
307 | Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/).
308 |
309 | To format our code whenever we make a commit in git, we need to install the following dependencies:
310 |
311 | ```sh
312 | npm install --save husky lint-staged prettier
313 | ```
314 |
315 | Alternatively you may use `yarn`:
316 |
317 | ```sh
318 | yarn add husky lint-staged prettier
319 | ```
320 |
321 | * `husky` makes it easy to use githooks as if they are npm scripts.
322 | * `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8).
323 | * `prettier` is the JavaScript formatter we will run before commits.
324 |
325 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root.
326 |
327 | Add the following line to `scripts` section:
328 |
329 | ```diff
330 | "scripts": {
331 | + "precommit": "lint-staged",
332 | "start": "react-scripts start",
333 | "build": "react-scripts build",
334 | ```
335 |
336 | Next we add a 'lint-staged' field to the `package.json`, for example:
337 |
338 | ```diff
339 | "dependencies": {
340 | // ...
341 | },
342 | + "lint-staged": {
343 | + "src/**/*.{js,jsx,json,css}": [
344 | + "prettier --single-quote --write",
345 | + "git add"
346 | + ]
347 | + },
348 | "scripts": {
349 | ```
350 |
351 | Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx,json,css}"` to format your entire project for the first time.
352 |
353 | Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://prettier.io/docs/en/editors.html) on the Prettier GitHub page.
354 |
355 | ## Changing the Page ``
356 |
357 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `` tag in it to change the title from “React App” to anything else.
358 |
359 | Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML.
360 |
361 | If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library.
362 |
363 | If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files).
364 |
365 | ## Installing a Dependency
366 |
367 | The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`:
368 |
369 | ```sh
370 | npm install --save react-router
371 | ```
372 |
373 | Alternatively you may use `yarn`:
374 |
375 | ```sh
376 | yarn add react-router
377 | ```
378 |
379 | This works for any library, not just `react-router`.
380 |
381 | ## Importing a Component
382 |
383 | This project setup supports ES6 modules thanks to Babel.
384 | While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead.
385 |
386 | For example:
387 |
388 | ### `Button.js`
389 |
390 | ```js
391 | import React, { Component } from 'react';
392 |
393 | class Button extends Component {
394 | render() {
395 | // ...
396 | }
397 | }
398 |
399 | export default Button; // Don’t forget to use export default!
400 | ```
401 |
402 | ### `DangerButton.js`
403 |
404 |
405 | ```js
406 | import React, { Component } from 'react';
407 | import Button from './Button'; // Import a component from another file
408 |
409 | class DangerButton extends Component {
410 | render() {
411 | return ;
412 | }
413 | }
414 |
415 | export default DangerButton;
416 | ```
417 |
418 | Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes.
419 |
420 | We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`.
421 |
422 | Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like.
423 |
424 | Learn more about ES6 modules:
425 |
426 | * [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281)
427 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
428 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
429 |
430 | ## Code Splitting
431 |
432 | Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand.
433 |
434 | This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module.
435 |
436 | Here is an example:
437 |
438 | ### `moduleA.js`
439 |
440 | ```js
441 | const moduleA = 'Hello';
442 |
443 | export { moduleA };
444 | ```
445 | ### `App.js`
446 |
447 | ```js
448 | import React, { Component } from 'react';
449 |
450 | class App extends Component {
451 | handleClick = () => {
452 | import('./moduleA')
453 | .then(({ moduleA }) => {
454 | // Use moduleA
455 | })
456 | .catch(err => {
457 | // Handle failure
458 | });
459 | };
460 |
461 | render() {
462 | return (
463 |
464 |
465 |
466 | );
467 | }
468 | }
469 |
470 | export default App;
471 | ```
472 |
473 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button.
474 |
475 | You can also use it with `async` / `await` syntax if you prefer it.
476 |
477 | ### With React Router
478 |
479 | If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app).
480 |
481 | Also check out the [Code Splitting](https://reactjs.org/docs/code-splitting.html) section in React documentation.
482 |
483 | ## Adding a Stylesheet
484 |
485 | This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**:
486 |
487 | ### `Button.css`
488 |
489 | ```css
490 | .Button {
491 | padding: 20px;
492 | }
493 | ```
494 |
495 | ### `Button.js`
496 |
497 | ```js
498 | import React, { Component } from 'react';
499 | import './Button.css'; // Tell Webpack that Button.js uses these styles
500 |
501 | class Button extends Component {
502 | render() {
503 | // You can use them as regular CSS styles
504 | return ;
505 | }
506 | }
507 | ```
508 |
509 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack.
510 |
511 | In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output.
512 |
513 | If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool.
514 |
515 | ## Post-Processing CSS
516 |
517 | This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it.
518 |
519 | For example, this:
520 |
521 | ```css
522 | .App {
523 | display: flex;
524 | flex-direction: row;
525 | align-items: center;
526 | }
527 | ```
528 |
529 | becomes this:
530 |
531 | ```css
532 | .App {
533 | display: -webkit-box;
534 | display: -ms-flexbox;
535 | display: flex;
536 | -webkit-box-orient: horizontal;
537 | -webkit-box-direction: normal;
538 | -ms-flex-direction: row;
539 | flex-direction: row;
540 | -webkit-box-align: center;
541 | -ms-flex-align: center;
542 | align-items: center;
543 | }
544 | ```
545 |
546 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling).
547 |
548 | ## Adding a CSS Preprocessor (Sass, Less etc.)
549 |
550 | Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `` and `` components, we recommend creating a `