Giter Site home page Giter Site logo

mynodesummary's People

Contributors

mxcz213 avatar

Watchers

 avatar  avatar

mynodesummary's Issues

(二)egg.js与前端打通,做到前后端分离

此文的目的是:让egg作为中间接口层,只出接口,前端做页面渲染,搞成前后端分离。

思路是:首先给前端启动一个服务,用http-server 或者 webpack-dev-server
后端启动一个服务,将前端代码打包之后的js,css文件通过script,link的方式引入到egg的模板文件里去。

一:http-server 启动一个前端服务

新建一个前端项目:

mkdir http-server-test
cd http-server-test
npm install http-server -g

新建一个test.html页面,随便写个hello world,然后运行

http-server

访问http://127.0.0.1:8080/test.html 得到下面页面

前端http server就启动好了。

二:前端项目通过webpack工具+react前端框架打包出js,css文件

1.进到http-server-test目录,npm init一路回车即可

npm init

2.安装相关依赖

//babel编译js相关
npm install babel-loader babel-core babel-preset-es2015 babel-preset-react --save-dev
//css文件处理相关
npm install css-loader style-loader less-loader postcss-loader less --save-dev
//将css达成独立的css文件
//加上@next是为了防止出错,遇到了这个坑
npm install extract-text-webpack-plugin@next --save-dev
//安装react框架相关
npm install react react-dom --save 
//webpack打包文件相关依赖
npm install webpack -g
npm install webpack --save-dev
//因为直接webpack打包的时候报错说是webpack-cli是独立出来的,所以也要安装一下
npm install webpack-cli --save-dev       

3.配置babel,新建一个.babelrc文件,写入如下代码

{
    "presets":["es2015","react"]
}

4.配置webpack文件,新建webpack.config.js文件,写入如下代码:

const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
    context:path.resolve(__dirname,''),
    entry:{
        main:'./src/index.jsx'
    },
    output:{
        path:path.resolve(__dirname,'dist/'),
        filename:'index.js'
    },
    module:{
        rules:[
            {
                test:/\.jsx$/,
                use:'babel-loader'
            },
            {
                test:/\.less$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: ["css-loader","less-loader"]
                  })
            }
        ]
    },
    plugins:[
        new webpack.DefinePlugin({
            'process.env.NODE_ENV':JSON.stringify('development'),
            __DEV__:true
        }),
        new ExtractTextPlugin('index.css'),
    ]
}

5.继续丰富目录,目路结构(dist目录是webpack打包自动生成的文件,不需要手动创建)如下:

//src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>hello</title>
</head>
<body>
    <div id="app"></div>
    <script src="../dist/index.js"></script>
</body>
</html>
//src/index.jsx
import React from 'react'
import ReactDOM from 'react-dom'
import HelloComponent from '../components/hello.jsx'
import './index.less'

ReactDOM.render(
    <div className="app-box">
        <HelloComponent />
    </div>,
    document.getElementById('app')
);
//src/index.less
.app-box{
    width:200px;
    height: 400px;
    margin:50px auto;
    border:1px solid #ccc;
}
//components/hello.jsx
import React from 'react'
import './hello.less'

export default class HelloComponent extends React.Component{
    render(){
        return(
            <div className="hello-box">hello world</div>
        );
    }
}
//components/hello.less
.hello-box{
    color:#f00;
}

6.运行webpack打包出文件

webpack --watch

三:将打包出来的css,js文件通过script src=""链接到egg.js的模板文件中

打开上一节新建的egg项目

//app/controller/home.js
const Controller = require('egg').Controller;
class HomeController extends Controller{
    async index(){
       await this.ctx.render('home/home.tpl');
    }
}
module.exports = HomeController;
//app/view/home/home.tpl
<html>
  <head>
    <title>Hacker News</title>
    <link rel="stylesheet" href="http://127.0.0.1:8080/dist/index.css" />
  </head>
  <body>
    <div id="app"></div>
    <script src="http://127.0.0.1:8080/dist/index.js"></script>
  </body>
</html>

最后命令行运行:

npm run dev

访问http://127.0.0.1:7001/

注意:前端的服务http-server,以及egg的服务都要开启。

结语:如此便实现egg.js负责接口服务,前端做前端的事,前后端分离。

(一)egg.js快速人门,跑出hello world

一:什么是egg.js?

egg.js是nodejs 的一个框架,是基于koa框架的基础上整合的一套上层框架,既定的目录结构,开发者只需要基于MVC模式,根据项目规范的目录结构,专注于编写相应的controller,service,router,view,config配置,以及plugin插件可扩展。

二:脚手架快速生成项目

1.系统和环境:windows + node 8以上

2.脚手架命令,快速初始化生成项目


npm i egg-init -g
egg-init egg-myProject --type=simple
cd egg-myProject
npm i

3.启动项目


npm run dev

4.浏览器中打开http://127.0.0.1:7001:

image

三:不用脚手架,逐步搭建,熟悉项目目录结构

1.初始化目录结构


mkdir egg-my-example
cd egg-my-example
npm init

npm init之后一路回车即可,然后安装egg  egg-bin:


npm i egg --save
npm i egg-bin --save-dev

2.找到package.json文件添加


"scripts": {

    "dev": "egg-bin dev"

  },

3.编写controller文件,router路由,添加配置文件config

在项目 egg-my-example 目录下新建app文件夹,新建controller文件夹,新建文件home.js

在项目 egg-my-example 目录下app文件夹新建router.js文件

在项目 egg-my-example 目录下新建与app同级的config文件夹,(注意:config文件夹跟app同级目录),新建config.default.js文件


//app/controllter/home.js

const Controller = require('egg').Controller;

class HomeController extends Controller{

    async index(){

        this.ctx.body = "hello world";

    }

}

module.exports = HomeController;


//app/router.js

module.exports = app => {

  const { router, controller } = app;

  router.get('/',controller.home.index);

  router.get('/list',controller.news.list);

}


//config/congif.default.js

exports.keys = '123456790';  //key是自己的cookie信息

整体项目目路结构如下:

image

4.运行项目


npm run dev

5.浏览器打开   http://127.0.0.1:7001

image

如此一个简单的hello world就完成了,手动新建项目过程中一定要注意目路结构,egg根据既定的项目目录,开发者可以专注编写controller等业务代码,快速完成项目。

6.接下来可以继续编写view模板文件
使用 Nunjucks来渲染,安装对应的插件 egg-view-nunjucks

npm i egg-view-nunjucks --save

开启插件:(config目录下新建plugin.js文件)

//config/plugin.js
exports.nunjucks = {
    enable:true,
    package:'egg-view-nunjucks'
}

添加view模板配置

//config/config.default.js
exports.view = {
    defaultViewEngine:'nunjucks',
    mapping:{
        '.tpl':'nunjucks'
    }
}

7.为一个列表页编写模板文件
在app目录下新建一个view文件夹,将所有模板文件放到view下

//app/view/news/list.tpl
<html>
  <head>
    <title>Hacker News</title>
    <link rel="stylesheet" href="/public/css/news.css" />
  </head>
  <body>
    <ul class="news-view view">
      {% for item in list %}
        <li class="item">
          <a href="{{ item.url }}">{{ item.title }}</a>
        </li>
      {% endfor %}
    </ul>
  </body>
</html>

添加controller,router

//app/controller/news.js
const Controller = require('egg').Controller;
class NewsController extends Controller {
   async list() {
    const dataList = {
      list: [
        { id: 1, title: 'this is news 1', url: '/news/1' },
        { id: 2, title: 'this is news 2', url: '/news/2' }
      ]
    };
    await this.ctx.render('news/list.tpl', dataList);
}
module.exports = NewsController;
//app/router.js
module.exports = app => {
   const { router, controller } = app; 
   router.get('/',controller.home.index);
   router.get('/list',controller.news.list);
}

8.浏览器中打开http://127.0.0.1:7001/list
image.png

参考:https://eggjs.org/zh-cn/intro/quickstart.html

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.