为Vue配置Webpack,以使后端Express Server位于ECMA2016中

时间:2019-03-07 15:41:05

标签: express vue.js webpack

我使用webpack-boilerplate为vue编写了一个应用。处理GETPOST请求的后端是一个express服务器。 IDE是Visual Studio代码。

这就是我所做的:

$ vue init webpack app
$ cd app
$ npm install
$ npm install axios express body-parser node-sass sass-loader
$ npm install --save-dev concurrently nodemon

app/express/app.js如下:

//import express from express
var express = require('express')
var app = express()
// sets port 8080 to default or unless otherwise specified in the environment
app.set('port', process.env.PORT || 8080)

var bodyParser = require('body-parser')    
app.use(bodyParser.json())

app.use(express.static(`${__dirname}/../dist/`))

// Test: curl -X POST -H "Content-Type: application/json" -d '{"path": "bla/blub.txt"}' http://localhost:8081/api/save
app.post('/api/save', function (req, res) {
    response = {
        msg: 'okay',
        data: Math.floor(Math.random() * 10)
    };
    res.end(JSON.stringify(response))
})

var server = app.listen(app.get('port'), function () {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port)
})

我修改了vue init webpack生成的样板代码,使得app/components/HelloWorld.vue为:

<template>
    <div>
        <h1>{{ msg }}</h1>
    </div>
</template>

<script>
import Axios from 'axios'
const baseUrl = "http://127.0.0.1:8080/api"
export default {
    name: 'HelloWorld',
    data () {
        return {
            msg: 'Welcome to Your Vue.js App'
        }
    },
    async created() {
        this.msg = await Axios.post(`${baseUrl}/save`, {"path": "bla/blub.txt"})
            .then(response => new Promise(resolve => {
                let msg = response.data.msg
                resolve(msg)
            }))
            .catch(error => {
                console.log(error)
                Promise.reject(error)
            })
    }
}
</script>

<style lang="scss" scoped>
h1 {
  font-weight: normal;
}
</style>

要在一个命令(npm start go中开始开发并允许热重装,我更改了app/package.json(不知道该复制自何处):

  "scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "apiserver": "PORT=8081 nodemon express/app.js",
    "go": "concurrently --kill-others \"npm run dev\" \"npm run apiserver\"",
    "start": "npm run dev",
    "build": "node build/build.js"
  },

要启动该应用程序的开发版本,我运行:

$ npm run dev   # webpack-dev-server starts on port 8080, express on 8081

为避免CORS问题,可以将webpack配置为代理快递请求。更改app/config/index.js

proxyTable: {
'/api':{
    target: 'http://localhost:8081',
    changeOrigin: true,
 }
},

现在可以再次从npm run dev运行app/,一切正常。

因此,进入生产模式。我跑

$ npm run build
$ node express/app.js

一切正常。

(随着时间的流逝,我在这个问题中添加了自己找到的答案...原始问题是:“为vue前端配置webpack并表达后端(场景包括生产和开发)”)

我的问题是:

如何更改webpack babel设置,以使node运行的文件app.js使用ECMA2016(这样就可以使用import express from express代替require ...)?

感谢您的帮助!

0 个答案:

没有答案