博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
node支持es6语法吗_如何使用Node和Express启用ES6(及以后)语法
阅读量:2526 次
发布时间:2019-05-11

本文共 18827 字,大约阅读时间需要 62 分钟。

node支持es6语法吗

Have you ever tried to write front-end apps using ES6 syntax, but then  when you decided to learn back-end development with Node.js and Express,  you realized that you can’t use stuff like import from and  export default?  If so, you came to the right place! This is step by step guide on how  to configure your dev and prod environments, setup scripts, and as a  bonus we’ll learn how to add tests!

您是否曾经尝试过使用ES6语法编写前端应用程序,但是当您决定学习使用Node.js和Express进行后端开发时,您意识到自己无法使用诸如import from export default import fromexport default类的东西? 如果是这样,那么您来对地方了! 这是有关如何配置开发和生产环境,设置脚本的分步指南,此外,我们还将学习如何添加测试!

目录/主题摘要 (Table of Contents / Summary of topics)

它是如何工作的? 全面了解我们的需求 (How does it work? A high level view of what we need)

To enable a front-end development-like experience while developing back-end apps, here’s a high level view of the processes happening to your project.

为了在开发后端应用程序时提供类似于前端开发的体验,下面是对项目中正在发生的过程的高级概述。

从ES6 +到ES5的代码转换器 (Code Transpiler from ES6+ to ES5)

We need a package that translates ES6 and above syntax to ES5 code. ES5 code is the JS syntax style that is readable to node.js, such as module.exports or var module = require('module') . Note that in today’s time, almost 99% of ES6+ syntax can be used in Node.js. This is where the package called shines.

我们需要一个将ES6及以上语法转换为ES5代码的软件包。 ES5代码是node.js可以读取的JS语法样式,例如module.exportsvar module = require('module') 。 请注意,在当今时代,Node.js中几乎可以使用99%的ES6 +语法。 这就是所谓的软件包的发亮之处。

Babel takes a js file, converts the code in it, and outputs into a new file.

Babel提取了一个js文件,将其中的代码转换为新文件。

删除文件的脚本 (Script that removes files)

Whenever we change something in our code, we feed it to the transpiler, and it outputs a fresh copy every-time. That’s why we need a script that removes files before the fresh transpiled copy enters. And for that, there’s an existing package called . Rimraf deletes files. We’ll demonstrate that later.

每当我们在代码中更改某些内容时,就会将其提供给编译器,并且每次都会输出一个新副本。 这就是为什么我们需要一个脚本,该脚本在输入新的转译副本之前先删除文件。 为此,有一个名为的现有软件包。 Rimraf删除文件。 稍后我们将进行演示。

监视文件更改 (Watcher of file changes)

When coding in Node.js, automatic restart of our server doesn’t come out of the box just like when doing a project made on-top of create-react-app or vue-cli. That’s why we’ll install a package called that executes something whenever we change a file in our code. We can leverage nodemon to restart our server every-time a file is changed.

在Node.js中进行编码时,就像在create-react-app或vue-cli上进行项目时一样,我们的服务器不会自动重启。 这就是为什么我们将安装一个名为的软件包的该软件包在我们更改代码中的文件时都会执行某些操作。 每当文件更改时,我们就可以利用nodemon重新启动服务器。

So that’s the high-level view of how it works under the hood. With that, let’s start on how should we setup or project.

因此,这是它在内部工作原理的高级视图。 这样,让我们​​开始如何设置或投影。

先决条件 (Prerequisites)

Before we begin, we need some things setup first.

在开始之前,我们需要先进行一些设置。

  1. Make sure you have Node.js and npm installed. I recommend installing their latest LTS or current stable version. You can install it via or (Node Version Manager)

    确保已安装Node.js和npm。 我建议安装其最新的LTS或当前的稳定版本。 您可以通过或 (节点版本管理器)安装它

  2. Basic knowledge of terminal commands. Most of the commands are in the tutorial anyway so you don’t have to worry about them.

    终端命令的基本知识。 无论如何,大多数命令都在本教程中,因此您不必担心它们。
  3. Make sure you have your terminal open and your favorite text editor installed.

    确保您已打开终端并安装了喜欢的文本编辑器。

That’s it, we’re good to go!

就是这样,我们很好!

安装Express (Installing Express)

Using the Express generator, we will create a new project with generated code, move some files, and convert some code to ES6 syntax. We need to convert it at this early stage because we need a way to verify if our ES6 code works.

使用Express生成器,我们将使用生成的代码创建一个新项目,移动一些文件,并将一些代码转换为ES6语法。 我们需要在早期阶段对其进行转换,因为我们需要一种方法来验证我们的ES6代码是否有效。

项目设置 (Project Setup)

Run this command in your terminal. You can name your-project-name with the name you like. --no-view flag means that we won’t be using any templating engine such as handlebars, ejs, or pug, for our skeleton Express app.

在终端中运行此命令。 您可以使用自己喜欢的名称来命名your-project-name--no-view标志表示我们的骨架Express应用程序将不使用任何模板引擎,例如把手,ejs或pug。

npx express-generator your-project-name --no-view

npx express-generator your-project-name --no-view

After creating your app, you need to go to your app directory. For Windows Powershell and Linux terminals, use:

创建应用程序后,您需要转到应用程序目录。 对于Windows Powershell和Linux终端,请使用:

cd your-project-name

cd your-project-name

Next, open the text editor you like. For me, I just use VSCode so I just have my terminal and text editor open at the same time. But you can use any text editor you want.

接下来,打开所需的文本编辑器。 对我来说,我只使用VSCode,所以我同时打开了终端和文本编辑器。 但是您可以使用任何所需的文本编辑器。

安装软件包以及移动和删除文件 (Installing Packages and Moving and Deleting Files)

After we have the generated project ready, we need to install the dependencies and move some folders. Run this command to install Express and other packages.

准备好生成的项目后,我们需要install依赖项并移动一些文件夹。 运行此命令以安装Express和其他软件包。

npm install

npm安装

While you’re waiting for the dependencies to install, follow these steps.

在等待安装依赖项时,请按照下列步骤操作。

  • create a server/ folder

    创建一个server/文件夹

  • Put bin/ , app.js , and routes/ inside the server/ folder.

    bin/ app.jsroutes/放在server/文件夹中。

  • Rename www, found in bin to

    重命名www ,在发现bin

  • Leave public/ folder at your project root.

    public/文件夹保留在项目根目录下。

Your file structure will look like this:

您的文件结构将如下所示:

Now, because we modified the file structure, our start server script won’t work. But we’ll fix it along the way.

现在,由于我们修改了文件结构,因此启动服务器脚本将不起作用。 但是我们会一路解决。

转换为ES6代码 (Converting to ES6 code)

Converting the generated code to ES6 is a little bit tedious, so I’ll just post the code here and feel free to copy and paste it.

将生成的代码转换为ES6有点繁琐,所以我将代码发布在这里,可以随意复制和粘贴。

Code for bin/www.js:

bin/www.js代码:

Now, because we modified the file structure, our start server script won’t work. Here’s what we’ll do to fix it. On your package.json file, rename start script to serverfound in a JSON Object called "scripts"

现在,由于我们修改了文件结构,因此启动服务器脚本将不起作用。 这是我们将对其进行修复的方法。 在package.json文件上,将启动脚本重命名为在名为"scripts"的JSON对象中找到的server

// package.json{  "name": "your-project-name",  // ....other details  "scripts": {    "server": "node ./server/bin/www"  }}

You’ll see that we changed the file path from ./bin/wwwto ./server/bin/www because we moved files to server/. We’ll use start script later on.

您会看到我们将文件路径从./bin/www./server/bin/www因为我们将文件移至server/ 。 稍后我们将使用启动脚本。

Try it! Try running the server by typing npm run server on your terminal, and go to localhost:3000 on your browser.

试试吧! 尝试通过在终端上键入npm run servernpm run server ,然后在浏览器上转到localhost:3000

转换顶级代码以使用ES6导入 (Converting the top level code to use ES6 imports)

Converting the generated code to ES6 is a little bit tedious, so I’ll just post the code here and feel free to copy and paste it.

将生成的代码转换为ES6有点繁琐,所以我将代码发布在这里,可以随意复制和粘贴。

Code for bin/www.js:

bin/www.js代码:

// bin/www.js/** * Module dependencies. */import app from '../app';import debugLib from 'debug';import http from 'http';const debug = debugLib('your-project-name:server');// ..generated code below.

Almost all of our modifications are only at the top and bottom of the files. We are leaving other generated code as is.

我们几乎所有的修改都只在文件的顶部和底部。 我们将保留其他生成的代码。

Code for routes/index.js and routes/users.js:

routes/index.jsroutes/users.js

// routes/index.js and users.jsimport express from 'express';var router = express.Router();// ..stuff belowexport default router;

Code for app.js:

app.js代码:

// app.jsimport express from 'express';import path from 'path';import cookieParser from 'cookie-parser';import logger from 'morgan';import indexRouter from './routes/index';import usersRouter from './routes/users';var app = express();app.use(logger('dev'));app.use(express.json());app.use(express.urlencoded({ extended: false }));app.use(cookieParser());app.use(express.static(path.join(__dirname, '../public')));app.use('/', indexRouter);app.use('/users', usersRouter);export default app;

In app.js , because we left public/ at the project root , we need to change the Express static path one folder up. Notice that the path 'public' became '../public' .

app.js ,由于我们将public/保留在项目根目录下,因此需要将Express静态路径更改为一个文件夹。 注意,路径'public'变成了'../public'

app.use(express.static(path.join(__dirname, '../public')));

app.use(express.static(path.join(__dirname, '../public')));

Okay we’re done with converting the code! Let’s setup our scripts now.

好的,我们已经完成了代码转换! 让我们现在设置脚本。

设置脚本 (Setting up Scripts)

In setting up scripts, each script performs a different role. And we reuse each npm script. And for our development and production environments, they have a different configuration. (Almost identical, you’ll see later) That’s why we need to compose our scripts so we can use them without repeatedly typing the same stuff all over again.

在设置脚本时,每个脚本执行不同的角色。 并且我们重复使用每个npm脚本。 对于我们的开发和生产环境,它们具有不同的配置。 (几乎完全相同,您将在后面看到)这就是为什么我们需要编写脚本,以便我们可以使用它们而无需再次重复键入相同内容的原因。

安装`npm-run-all` (Install `npm-run-all`)

Since some terminal commands won’t work on windows cmd, we need to install a package called npm-run-all so this script will work for any environment. Run this command in your terminal project root.

由于某些终端命令在Windows cmd上不起作用,因此我们需要安装一个名为npm-run-all的软件包,以便该脚本适用于任何环境。 在终端项目根目录中运行此命令。

npm install --save npm-run-all

npm install --save npm-run-all

安装babel,nodemon和rimraf (Install babel, nodemon, and rimraf)

Babel is modern JavaScript transpiler. A transpiler means your modern JavaScript code will be transformed to an older format that Node.js can understand. Run this command in your terminal project root. We will be using the latest version of babel (Babel 7+).

Babel是现代JavaScript翻译器。 编译器意味着您的现代JavaScript代码将转换为Node.js可以理解的旧格式。 在终端项目根目录中运行此命令。 我们将使用最新版本的babel(Babel 7+)。

Note that Nodemon is our file watcher and Rimraf is our file remover packages.

请注意,Nodemon是我们的文件监视程序,而Rimraf是我们的文件删除程序包。

npm install --save nodemon rimraf

npm install --save nodemon rimraf

添加转译脚本 (Adding transpile script)

Before babel starts converting code, we need to tell it which parts of the code to translate. Note that there are a lots of configuration available, because babel can convert a lot of JS Syntaxes for every different kinds of purpose. Luckily we don’t need to think about that because there’s an available default for that. We are using default config called as preset-env (the one we installed earlier) in our package.json file to tell Babel in which format we are transpiling the code.

在babel开始转换代码之前,我们需要告诉它要翻译的代码部分。 请注意,有很多可用的配置,因为babel可以为每种不同的目的转换很多JS语法。 幸运的是,我们不需要考虑这一点,因为有一个可用的默认值。 我们在package.json文件中使用称为default-env的默认配置(我们先前安装的默认配置)来告诉Babel我们正在以哪种格式编译代码。

Inside your package.json file, create a "babel" object and put this setting.

在您的package.json文件中,创建一个"babel"对象并放置此设置。

// package.json{    // .. contents above  "babel": {    "presets": ["@babel/preset-env"]  },}

After this setup we are now ready to test if babel really converts code. Add a script named transpile in your package.json:

设置完成后,我们现在可以测试babel是否真的转换了代码。 在package.json添加一个名为transpile的脚本:

// package.json"scripts": {    "start": "node ./server/bin/www",    "transpile": "babel ./server --out-dir dist-server",}

Now what happened here? First we need to run the cli command babel , specify the files to convert, in this case, the files in server/ and put the transpiled contents in a different folder called dist-server in our project root.

现在这里发生了什么? 首先,我们需要运行cli命令babel ,指定要转换的文件,在这种情况下,将文件存储在server/ ,并将已转译的内容放在我们项目根目录中的另一个名为dist-server文件夹中。

You can test it by running this command

您可以通过运行以下命令进行测试

npm run transpile

npm run transpile

You’ll see a new folder pop up.

您会看到一个新的文件夹弹出。

Yay it worked! ✅ As you can see, there’s a folder that has the same folder structure as our server folder but with converted code inside. Pretty cool right? Next step is to run try if our server is running!

是的,它起作用了! you如您所见,有一个文件夹与我们的服务器文件夹具有相同的文件夹结构,但内部包含转换后的代码。 很酷吧? 下一步是如果我们的服务器正在运行,请尝试运行!

清理脚本 (Clean script)

To have a fresh copy every-time we transpile code into new files, we need a script that removes old files. Add this script to your package.json

为了每次将代码转换为新文件时都有一个新副本,我们需要一个删除旧文件的脚本。 将此脚本添加到package.json

"scripts": {  "server": "node ./dist-server/bin/www",  "transpile": "babel ./server --out-dir dist-server",  "clean": "rimraf dist-server"}

This npm script that we made means it removes the folder dist-server/

我们制作的这个npm脚本意味着它删除了文件夹dist-server/

Now to combine transpile and clean, add a script called build , which combines the two processes.

现在,要结合使用transpile和clean,请添加一个名为build的脚本,该脚本结合了这两个过程。

// scripts"build": "npm-run-all clean transpile"

运行开发脚本 (Running dev script)

Now we have a build script, we need to run our dev server. We’ll add a script called dev in our package.json. This takes care of setting our Node Environment to “development”, removing old transpiled code, and replacing it with a new one.

现在我们有了一个构建脚本,我们需要运行我们的开发服务器。 我们将在package.json中添加一个名为dev的脚本。 这需要将节点环境设置为“开发”,删除旧的已编译代码,然后将其替换为新代码。

"scripts": {  "build": "npm-run-all clean transpile"  "server": "node ./dist-server/bin/www",  "dev": "NODE_ENV=development npm-run-all build server",  "transpile": "babel ./server --out-dir dist-server",  "clean": "rimraf dist-server"}

Note here that we’ve changed again the file we are running on our server script. We’re running the file-path with the transpiled code, found in dist-server/.

请注意,这里我们再次更改了在服务器脚本上运行的文件。 我们正在使用在dist-server/找到的已转换代码运行文件路径。

添加产品脚本 (Adding prod scripts)

If we have a dev script that sets the Node Environment to development, we have a prod script that sets it to “production.” We use this configuration when we are deploying. (Heroku, AWS, DigitalOcean, etc..) We’re now adding again our start script and prod script in our package.json again.

如果我们拥有将Node Environment设置为开发的dev脚本,那么我们就有了prod脚本将其设置为“生产”。 部署时使用此配置。 (Heroku,AWS,DigitalOcean等。)现在,我们再次在package.json中添加启动脚本和生产脚本。

"scripts": {  "start": "npm run prod"  "build": "npm-run-all clean transpile"  "server": "node ./dist-server/bin/www",  "dev": "NODE_ENV=development npm-run-all build server",  "prod": "NODE_ENV=production npm-run-all build server",  "transpile": "babel ./server --out-dir dist-server",  "clean": "rimraf dist-server"}

We set start script default to prod because start script is being used always by deployment platforms like AWS or Heroku to start a server.

我们将start脚本默认设置为prod,因为启动脚本始终被AWS或Heroku等部署平台用来启动服务器。

Try either by running npm start or npm run prod .

通过运行npm startnpm run prod尝试。

// package.json..."nodemonConfig": {   "exec": "npm run dev",  "watch": ["server/*", "public/*"],  "ignore": ["**/__tests__/**", "*.test.js", "*.spec.js"]},"scripts": {   // ... other scripts  "watch:dev": "nodemon"}

如何在文件更改时自动重新启动服务器? (How about auto-restarting the server whenever a file change?)

One final script, in order to complete our development setup. We need to add a file watcher script that runs a command whenever a change is made in a file. Add a JSON Object named “nodemonConfig” in your package.json. This is where we store what we tell the watcher what to do when a file changes.

最后一个脚本,以完成我们的开发设置。 我们需要添加一个文件监视程序脚本,只要在文件中进行更改,该脚本就会运行命令。 在package.json中添加一个名为“ nodemonConfig”的JSON对象。 在此存储文件,告诉文件更改时告诉观察者该做什么。

Also, add a script called watch:dev in your package.json

另外,在package.json中添加一个名为watch:dev的脚本。

// package.json..."nodemonConfig": {   "exec": "npm run dev",  "watch": ["server/*", "public/*"],  "ignore": ["**/__tests__/**", "*.test.js", "*.spec.js"]},"scripts": {   // ... other scripts  "watch:dev": "nodemon"}

Nodemon config contains settings related to

Nodemon配置包含与以下内容相关的设置

  • Which command to run whenever a file changes, in our case npm run dev

    每当文件更改时要运行哪个命令,在本例中为npm run dev

  • What folders and files to watch

    要观看的文件夹和文件
  • And which files to ignore

    以及哪些文件要忽略

More about configuration of nodemon .

更多关于nodemon的配置在 。

Now that we have our file watcher, you can now just run npm run watch:dev , code, and save your file. and whenever you go to localhost:3000 , you’ll see the changes. Try it out!

现在我们有了文件监视程序,您现在可以运行npm run watch:dev ,代码并保存文件。 每当您访问localhost:3000 ,您都会看到更改。 试试看!

奖励:添加测试! (Bonus: Add tests!)

To add tests in our project, simply install from npm, add a few config, and add a script called test in our package.json

要在我们的项目中添加测试,只需从npm安装 ,添加一些配置,然后在package.json中添加一个名为test的脚本即可。

npm i -D jest

npm i -D jest

Add an object called “jest”, and a test script in your package.json

在package.json中添加一个名为“ jest”的对象和一个测试脚本

// package.json..."jest": {   "testEnvironment": "node"},"scripts": {  // ..other scripts   "test": "jest"}

Try it out, make a file sample.test.js, write any tests, and run the script!

试试看,创建一个文件sample.test.js,编写任何测试,然后运行脚本!

npm run test

npm run test

TL; DR (TL;DR)

Here are the simplified steps for how to enable ES6 in Node.js. I’ll also include the repo so you can copy and inspect the whole code.

这是有关如何在Node.js中启用ES6的简化步骤。 我还将包括该存储库,以便您可以复制和检查整个代码。

  • Make a new project using express your-project-name terminal command.

    使用express your-project-name terminal命令创建一个新项目。

  • Move the bin/, routes/ and app into a new folder called src/ , and convert the code into ES6. Also don’t forget to rename bin/www to

    bin/routes/app移到名为src/的新文件夹中,并将代码转换为ES6。 同样不要忘记将bin/www重命名为

  • Install all the dependencies and devDependencies

    安装所有依赖项和devDependencies
npm i npm-run-all @babel/cli @babel/core @babel/preset-env nodemon rimraf --savenpm i -D jest
  • Add these scripts to your package.json

    将这些脚本添加到package.json
"scripts": {   "start": "npm run prod",   "build": "npm-run-all clean transpile",   "server": "node ./dist-server/bin/www",   "dev": "NODE_ENV=development npm-run-all build server",   "prod": "NODE_ENV=production npm-run-all build server",   "transpile": "babel ./server --out-dir dist-server",   "clean": "rimraf dist-server",   "watch:dev": "nodemon",   "test": "jest" }
  • Put configurations for babel, nodemon, and jest in your package.json

    将babel,nodemon和jest的配置放入package.json中
"nodemonConfig": {  "exec": "npm run dev",  "watch": [ "server/*", "public/*" ],  "ignore": [ "**/__tests__/**", "*.test.js", "*.spec.js" ] }, "babel": {   "presets": [ "@babel/preset-env" ]},"jest": {  "testEnvironment": "node"},
  • Test your scripts by running npm run your-script-here

    通过运行npm run your-script-here测试脚本, npm run your-script-here

  • You’ll see the

    您会看到

注释和免责声明 (Notes and disclaimers)

Note that this setup may not be proved ideal for all situations, specially for big projects. (like 1k files of code). Transpiling step and deleting might slow down your development environment. Plus, ES Modules, is almost coming to node. But, nevertheless, this is a good eductational material to understand how transipiling runs under the hood like when we are developing front-end apps :)

请注意,可能无法证明此设置适用于所有情况,尤其是大型项目。 (例如1k的代码文件)。 转译步骤和删除操作可能会减慢您的开发环境。 另外,ES模块几乎即将出现。 但是,尽管如此,这是一本很好的教育材料,可以帮助您了解如何像开发前端应用程序一样在后台进行透传:)

结论 (Conclusion)

All right! I hope you learned a lot. Thank you for reading this far.

行! 希望您能学到很多。 感谢您阅读本文。

Happy Coding!

编码愉快!

This article is published in freeCodecamp news.

本文发表在freeCodecamp新闻上。

- -   -

- -

翻译自:

node支持es6语法吗

转载地址:http://hozzd.baihongyu.com/

你可能感兴趣的文章
Ubuntu 12.04 添加新用户并启用root登录
查看>>
20145309信息安全系统设计基础第9周学习总结上
查看>>
c# 字段、属性get set
查看>>
td内容超出隐藏
查看>>
Spring CommonsMultipartResolver 上传文件
查看>>
Settings app简单学习记录
查看>>
SQLAlchemy
查看>>
多线程
查看>>
使用缓存的9大误区(下)转载
查看>>
appium键值对的应用
查看>>
MyEclipse 8.X 通用算法
查看>>
selenium.Phantomjs设置浏览器请求头
查看>>
Java Bigdecimal使用
查看>>
SQL注入之绕过WAF和Filter
查看>>
jquery validate使用方法
查看>>
DataNode 工作机制
查看>>
windows系统下安装MySQL
查看>>
错误提示总结
查看>>
实验二+070+胡阳洋
查看>>
Linux IPC实践(3) --具名FIFO
查看>>