使用應用程式產生器工具,express-generator
,快速建立應用程式架構。
你可以使用 npx
指令執行應用程式產生器(Node.js 8.2.0 中提供)。
$ npx express-generator
對於較早的 Node 版本,請將應用程式產生器安裝為全域 npm 套件,然後啟動它
$ npm install -g express-generator
$ express
使用 -h
選項顯示指令選項
$ express -h
Usage: express [options] [dir]
Options:
-h, --help output usage information
--version output the version number
-e, --ejs add ejs engine support
--hbs add handlebars engine support
--pug add pug engine support
-H, --hogan add hogan.js engine support
--no-view generate without view engine
-v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
--git add .gitignore
-f, --force force on non-empty directory
例如,以下會建立一個名為 myapp 的 Express 應用程式。應用程式會在目前工作目錄中建立一個名為 myapp 的資料夾,並將檢視引擎設定為 Pug
$ express --view=pug myapp
create : myapp
create : myapp/package.json
create : myapp/app.js
create : myapp/public
create : myapp/public/javascripts
create : myapp/public/images
create : myapp/routes
create : myapp/routes/index.js
create : myapp/routes/users.js
create : myapp/public/stylesheets
create : myapp/public/stylesheets/style.css
create : myapp/views
create : myapp/views/index.pug
create : myapp/views/layout.pug
create : myapp/views/error.pug
create : myapp/bin
create : myapp/bin/www
然後安裝相依性
$ cd myapp
$ npm install
在 MacOS 或 Linux 上,使用此指令執行應用程式
$ DEBUG=myapp:* npm start
在 Windows 命令提示字元中,使用此指令
> set DEBUG=myapp:* & npm start
在 Windows PowerShell 中,使用此指令
PS> $env:DEBUG='myapp:*'; npm start
然後在瀏覽器中載入 https://127.0.0.1:3000/
來存取應用程式。
產生的應用程式具有下列目錄結構
.
├── app.js
├── bin
│ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
└── views
├── error.pug
├── index.pug
└── layout.pug
7 directories, 9 files
產生器建立的應用程式結構只是建構 Express 應用程式的其中一種方法。請隨時使用此結構或修改它以最符合您的需求。