The last six months they have been writing a lot about the unjustified complexity of client-side JavaScript. A recent article How it feels to learn JavaScript in 2016 and its Habré translation has received much attention, criticism is largely fair, but ...
Complicate is simple, difficult to simplify. (One of the laws of Murphy)
In this article, I will give practical advice on how you can easily make a front-end application using modern technologies. Initially, the practical implementation details, and at the end of the article there will be an analysis of the selected stack.
As an example, the application is used to work with the collection of films. Movies are displayed in a list with page selection, search, sorting, editing, and deletion.
Used stack: create-react-app as a client build, React, bootstrap, API with json-server or json-stub.
The running demo is here: Movies List .
In the already mentioned article, there is a dialogue between an experienced front-end developer and a back-end developer who knows a little front-end and wants to write a simple client application using modern technologies. The front-end "guru" throws out all the variety of technologies that can be used, and so perplexes his colleague that he refuses his idea in general or decides to write everything in the old way with JQuery.
I will try to give more practical advice on how to do this, moreover, I will show the code of the finished application so that you can use it as an example.
GitHub repository is here .
The first problem in modern front-end development is the need for client builds. We will use a ready-made build system, where everything immediately works out of the box.
Create-react-app or React Scripts is a young project (first committee in June 2016) created by Dan Abramov, the creator of Redux, who now works on facebook.
To start
# create-react-app npm i -g create-react-app # my-app create-react-app my-app
React-scripts builds a client application, without the need for additional configuration. 2 development and production modes are supported.
In development mode, client assemblies are used in memory (with WebPack dev-server), hot-reload works immediately (you change the code, the page is reloaded), the code is checked with a linker (for example, if you have an unused variable, there will be a corresponding warning) and other.
To run in development mode, simply:
#cd my-app npm start
If you need to make a production assembly:
npm run build
This will create the application build in the "/ build" folder, where there will be a minimized and scan-ready version.
For importing styles and paths to images, the WebPack method is used, just import for the necessary resources.
// bootstrap npm import '../node_modules/bootstrap/dist/css/bootstrap.css'; // , somePicture import somePicture from '../media/picture.png';
Read more about working with react-scripts on the project's GitHub page .
We choose React as the JS framework. There are other good options (VueJS, Angular2), but unlike them, React has the most stable ecosystem. This means the stability of the API (does not change much from version to version), support in the IDE, a well-established set of additional libraries (Redux, react-router), a set of ready-made components (react-bootstrap, material-ui).
In this case, the syntax itself React JSX is not easy for a beginner and this is probably the most difficult thing to deal with in the selected stack.
The movies-list application itself is intentionally written simply to make it easier to understand for beginners (for example, in a real application you can make a more detailed breakdown into components).
There are a huge number of various React tutorials, for the selected stack, you need to use the ES6 syntax in the tutorial (components are declared through the class), and you do not need to learn Redux or React Router. You can deal with them later if need be.
An example of such a textbook can be React Fundamentals on Eggheads , you should also read the official documentation .
Modules are used as npm packages. As a CSS frame, “bootstrap” is used. Reeact-bootstrap components are used to integrate with React (well described on the project website).
The "toastr" package is used for pop-up error messages or notification of a successful operation (for example: the movie was saved). This package requires the inclusion of "jquery" and for a real project it may make sense to find an analogue on React, in order not to include jQuery and reduce the size of the packaged application.
To select multiple values ​​for the movie genre, use "react-select" - an advanced version of the component for the drop-down list.
When using ES6 classes, you need to do a bind for functions. The "react-autobind" package simplifies this task, it can potentially affect performance (you bind all methods, not only those where it is needed), but it makes development easier. Read more about bind in React here .
//: constructor() { super() this.update = this.update.bind(this); //... } //c autobind import autoBind from 'react-autobind'; ... constructor() { super() autoBind(this); }
For more convenient manipulation of css classes, the "classnames" package is used.
import classnames from 'classnames'; let oneClass = classnames('foo', 'bar'); // "foo bar" let isActive = true; let anotherClass = classnames({ 'foo': true, 'bar': false, 'active': isActive }) // "foo active"
If you do not have the ability or desire to use the server part for the client application, then there are several alternative possibilities:
JSON stubs - the initial application data is stored in a JSON file that is imported as an external resource.
import jsonData from '../myJsonFile.json';
In the future, all operations take place already with the loaded data. You implement search, edit, delete operations yourself, working with initial data from JSON.
In the movie-list, this approach is used by default, the logic in the 'movieServiceStubs' file.
Using json-server — the json-server package on startup gives access to the API set based on the JSON file structure.
For example, if you have db.json in which there is an array of movies, the following APIs will automatically be available:
GET /movies GET /movies/1 POST /movies PUT /movies/1 PATCH /movies/1 DELETE /movies/1
At the same time, the API changes the source db.json file; for GET requests, search, paging, sorting is supported.
In addition, json-server supports many additional options - custom routes, auto-generation of test data, support for connections between different elements.
In the movie-list there is an opportunity to work with json-server, you need to use movieService instead of movieServiceStub, except for this:
# json-server npm i -g json-server ## json-server npm-scripts npm run server
For AJAX requests in React Scripts it is suggested to use the fetch API. This is a new browser standard, which is more convenient than XMLHttpRequest. React Scripts uses a poly file to support older browsers.
Unlike jQuery, axios and other client libraries, Fetch is a standard that you can use now and that will be serious and for a long time.
In order not to complicate the code with additional libraries, in the movie-list I use only ES6 features (without lodash)
In addition to the switch functions ((x) => ...), you should pay attention to such as:
» Template lines
» Iteration of the for ... of ... collection
» Cloning an Object with Object.assign
» Methods of arrays map, filter, reduce
Thanks to the new features of ES6, Lodash and similar libraries no longer have such an urgent need, although their use may still be useful.
The project does not use ES2016 + features, they are supported by React Scripts , but APIs are less reliable and worse supported (documentation, examples, support in IDE, etc.). If you're still interested, you can try using async / await instead of Promise and static properties in React components.
There are many sites on which you can lay out static resources (HTML / CSS / JS). React Scripts suggests using GitHub pages for this, the documentation describes how to do this and after 5 minutes of setup you can publish a demo version of your application. At the same time, it is necessary to use json stubs, which means the application will lose its state after the page is completely overloaded, which is even better for the demo.
The article already mentioned indicates several problems of the modern front-end:
First, why are they needed at all? Why it is impossible as before to just include the script in the HTML pages and just start writing code.
Basically, due to the fact that some browsers implement new standards very slowly (we will not point with our fingers, but mostly this concerns IE). Until these browsers go down in history (which is at least a couple of years), there will be a need for client builds, at least in order to use the new features of the ES6 language. In addition, if you have a large application, then you should minify your code, and if it is split into many files, merge them into one assembly, taking into account the links (if module A uses module B, then module B must be included before module A).
It is difficult to customize the client build. You need to connect the webpack, babel, with a dozen webpack loaders, to support the dev / prod assembly. This can take a lot of time and nervous experiences, even when using a boilerplate, it will not be easy for you to choose it, and then maintain it. Fortunately, there are collectors (not many yet) for the client application, in which everything is hidden inside a separate package and all you need is to connect this collector and write your application with certain features.
There are already analogs of React Scripts, for VueJS this is vbuild , for Angular2 I haven’t yet seen an alternative, but there is a build system for Ionic2 which is built on Angular2. These projects are not yet so run-in, but the emergence of such tools is only a matter of time.
Some doubt that this is suitable for serious applications. This is quite possible, but when using a ready-made client-side system, you must abide by some agreements, for example, the entry point is one and is in src / index.js, CSS preprocessors are not used, the code is checked by a certain set of linter rules. At the same time, the application itself can be either a simple "hello world" or a complex client on many pages. For example, in the project Contoso Express, react scripts are used for a much more complex application.
In the end, if after a few months you need something that cannot be achieved by a ready-made collector, you can make your custom decision, but you don’t have to do it at the very beginning.
You learn a new technology, spend a lot of time, and it becomes obsolete after six months or the new version of the API is changing dramatically and you have to figure it out again.
This is true for many technologies, the price of progress, but not for all. If you do not want to face a similar situation, you just need to choose the right stack. In our stack, most technologies have long existed, they work reliably and will not change much in the future.
It is impossible to speak with full confidence about React (although after switching to the ES6 syntax, for the components there were no significant changes in the basic syntax). But as for ES6, Fetch, Promises - this is something that is already the JS standard and will be relevant for many years, and is already supported in most browsers.
The ability to choose the right tools is important not only in programming. The problem with JS is that there is no mainstream approach for most cases, like for example in .NET. And the choice is much more complicated. In this regard, the React ecosystem is fairly well established, for example, if at the beginning there were many Flux implementations for React, now most applications use Redux, there is only one popular version for client routing React Router, etc.
It is important not to use unnecessary tools using a progressive development process. Start with the necessary minimum, adding new components only when it is really necessary. For example, in the aforementioned article, for a simple one-page application, some technologies were proposed that did not make sense at all:
Thanks to those who read to the end.
Happy coding! Stay tuned.
Source: https://habr.com/ru/post/313234/
All Articles