這裏供應手動搭建vue單頁面開闢臨盆環境,並運用node寫背景代碼,僅供小白參考;
代碼雖然沒多少,但牽涉的學問許多,須要逐一研討;
後續內容《手動搭建vue+node單頁面(二)》
https://segmentfault.com/a/11…
項目地點:https://github.com/liubingyan…
內容提要:vue2,webpack,express,router,jsonp,這一章會從0到開闢環境,臨盆環境的搭建:
思緒:
先完成webpack單頁面的demo
->
然後完成express效勞下的開闢環境
->
再完成開闢·臨盆環境的切換
->
末了做營業相干的頁面和後端開闢
一、建立項目:
1.初始化項目:在桌面新建文件夾test,在test目次下命令行輸入npm init -y;
2.test下建立src文件夾(前端一切代碼);
build文件夾(打包相干的webpack設置文件);
service文件夾(寄存後端代碼);
data文件夾(寄存json數據);
server.js(node效勞)
二、下面我們先做單頁面,先不論效勞的事變
在src目次中建立views(寄存一切.vue組件),router(寄存前端路由設置),store(寄存vuex設置),man.js(單頁面進口文件),app.vue(單頁面首頁組件),test下建立index.html作為載體。
接下來要做幾件事完成單頁面demo:
(1)編寫進口文件main.js
//main.js
const Vue from 'vue'
const App from './app'
new Vue({
el:'#app',
render:h=>h(App)
})
(2)單頁面主體app.vue;
//app.vue
<template>
<div>
{{msg}}
</div>
</template>
<script>
export default{
data(){
return {
msg:'this is my app!'
}
}
}
</script>
<style lang='less'>
</style>
(3)接下來是設置文件:在build文件夾中建立webpack.config.js
//webpack.config.js
const path = require('path')
module.exports = {
mode:'development',//webpack4新加的,不寫會報黃
entry: {
main: path.resolve(__dirname, '../src/main.js')
},
output: {
path: path.resolve(__dirname, '../dist'),
publicPath: 'http://localhost:3000/',
filename: '[name].js'
},
module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
'less': [
'vue-style-loader',
'css-loader',
'less-loader'
]
}
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},]
},
resolve: {
alias: {//開闢環境運用vue.esm.js',官網有申明
'vue$': 'vue/dist/vue.esm.js'
},
//reuqire加載文件會自動為以下後綴的文件(如:./app.vue能夠寫成./app了)
extensions: ['*', '.js', '.vue', '.json']
},
}
接下來就是要啟動項目了,不過要先裝置種種插件
vue
vue-loader
webpack
css-laoder
sass-loader
vue-style-loader
babel-loader
````
不全,缺什麼依據提醒逐步裝
應為終究我們啟動項目是用server.js啟動,所以在這裏我們如許寫
//server.js
const webpack=require('webpack')
const webpackConfig=require('./build/webpack.config')
webpack(webpackConfig,function(err,stats){
if(err) throw err
//輸出打包信息(不必在乎這些細節)
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
})
然後實行打包(在test目次下)
node server
爆紅就好悅目看是語法錯誤照樣少插件,一會兒就可以處理。
看下結果,遺忘,index.html要先寫成:
//index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id='app'></div>
</body>
</html>
<script type="text/javascript" src="./dist/main.js"></script>
翻開index.html看看結果。
三、最先完成express啟服和熱加載
接下來用express啟服,同時完成webpack的熱加載和server.js的熱加載;
1.修正設置server.js
//server.js
const webpack=require('webpack')
const webpackConfig=require('./build/webpack.config')
//dev和hot用來完成前端的熱加載
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const express=require('express')
const path=require('path')
const app=express()
const compiler = webpack(webpackConfig)//刪除了打印的回調函數,加上的話這裡會實行兩遍打包,不曉得為啥
app.use(webpackDevMiddleware(compiler,{
// public path should be the same with webpack config
//在項目中如許的途徑都邑設置到一致的文件中
publicPath: 'http://localhost:3000/',
noInfo: true,
stats: {
colors: true
}
}))
app.use(webpackHotMiddleware(compiler))
app.listen(3000,function(){
console.log('App is now running on port 3000!');
})
2.修正兩個處所:webpack設置和index.html
// webpack.config.js
const path = require('path')
const webpack=require('webpack')
const htmlPlugin=require('html-webpack-plugin')
//增添頁面熱加載字段,添加到entry中(牢固寫法)
const hotMiddlewareScript = 'webpack-hot-middleware/client?reload=true'
module.exports = {
mode: 'development',
entry: {
//就是如許寫就對 了
main: [path.resolve(__dirname, '../src/main.js'),hotMiddlewareScript]
},
output: {
path: path.resolve(__dirname, '../dist'),
publicPath: 'http://localhost:3000/',
filename: '[name].js'
},
module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
'scss': [
'vue-style-loader',
'css-loader',
'less-loader'
]
}
}
}, {
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
}, ]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
//新增html插件,天生main.js的同時天生index.html
plugins:[
new htmlPlugin({
template:'index.html'
}),
//熱加載須要運用這個插件才起作用
new webpack.HotModuleReplacementPlugin(),
]
}
然後index.html修改就是刪除本身寫的script標籤就好。
3.啟動項目之前全局裝置一個插件:(前端有了熱加載,這個是為了後端的熱加載,修正效勞或許打包設置文件不必手動重啟效勞。)
npm i supervisor -g
然後修正package.json中的scripts
//package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
//這句話是說:監控(-w)后定義的文件或許文件夾 -e示意-w監控的文件夾中的js文件發生變化時重啟server.js
"start": "supervisor -w server,build,server.js -e js server"
},
4.接下來激動人心的時候,啟動:
npm run start
翻開localhost:3000
按下f12看看有無報錯,鐺鐺鐺鐺,沒有報錯,如今已完成了一個簡樸但功用完美的開闢環境;
四、署下臨盆環境
布置臨盆環境我們要做幾件事:
1.build新建config.js,設置一些通用設置;
2.build新建webpack.config.dev.js,辨別開闢形式和臨盆形式的設置,實在能夠寫在一個文件中,弊病就是代碼太長,而且開闢形式require()的組件比較多,臨盆形式沒必要加載,所以離開;
3.修正server.js,webpack.js和package.json文件;
我們先修正package.json
//經由過程設置node環境中process.ENV屬性,來通知webpack和server應當運轉在哪一個環境,cross-env NODE_ENV就是用來設置process.ENV的;
//package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "supervisor -w server,build,server.js -e js,html server",
"dev": "cross-env NODE_ENV=development supervisor -w server,build,server.js -e js,html server",
"pro": "cross-env NODE_ENV=production node server"
},
cross-env須要裝置下
npm i cross-env -save
再運轉開闢環境就用npm run dev ,臨盆就用npm run pro
接下來在build文件夾下建立並設置config.js
//config.js
//簡樸設置夠用就好,完全的設置能夠到vue百口桶中進修
const path=require('path')
let isdev=process.env.NODE_ENV=='development'?true:false
let config={
isdev:isdev,
publicPath:'http://localhost:3000/',
port:'3000'
}
module.exports=config
在build下建立並編輯webpack.dev.config.js(把之前的webpack.config.js複製一下)
//webpack.config.dev.js(只展現差別的處所)
//....
//新增通用設置文件
const config = require('./config')
//....
output: {
path: path.resolve(__dirname, '../dist'),
publicPath: config.publicPath,//就是修正了輸出的公網途徑為設置文件中的途徑
filename: '[name].js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
//刪除html模板(後面會詮釋)
//new htmlPlugin({
// template:'index.html'
// }),
]
//....
接下來修正webpack.config.js為臨盆環境設置(一樣只列出差別的處所)
//webpack.config.js
const config = require('./config')
//刪除熱加載
//const hotMiddlewareScript = 'webpack-hot-middleware/client?reload=true'
//新增文件消滅插件
const cleanWebpackPlugin = require('clean-webpack-plugin')
//....
entry: {
main:path.resolve(__dirname, '../src/main.js')//作廢熱加載
},
output: {
path: path.resolve(__dirname, '../dist'),
publicPath: config.publicPath,
filename: '[name].js'
},
//....
resolve: {
alias: {
'vue$': 'vue/dist/vue.min.js'//臨盆運用緊縮的vue文件
},
extensions: ['*', '.js', '.vue', '.json']
},
plugins: [
//刪除熱加載
//new webpack.HotModuleReplacementPlugin(),
//刪除html模板(後面會詮釋)
//new htmlPlugin({
// template:'index.html'
// }),
//增添dist刪除選項
new cleanWebpackPlugin(['dist'], {
"root": path.resolve(__dirname, '../'),
})
]
//....
末了修正server文件,以為長能夠試着分紅開闢臨盆兩個文件
//server.js
const webpack = require('webpack')
const webpackConfig = require('./build/webpack.config')
const webpackDevConfig = require('./build/webpack.config.dev')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const express = require('express')
const path = require('path')
//新增config和swig插件
const config = require('./build/config')
const swig = require('swig')
const app = express()
//swig一款js模板引擎,是效勞端向客戶端返回html的一種體式格局,swig只是浩瀚引擎中的一種;
//這裏經由過程node向頁面返回html,而不是直接接見dist中的index.html,所以到這裏已把webpack中的html模板刪掉了;
//假如運用webpack運用html插件,在切換臨盆和開闢須要手動修正html的script;
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', path.resolve(__dirname, './'));
app.get('/', function(req, res) {
res.type('text/html');
res.render('index');
});
if (config.isdev) {
console.log('server運轉在開闢環境')
const compiler = webpack(webpackDevConfig)
app.use(webpackDevMiddleware(compiler, {
// public path should be the same with webpack config
publicPath: 'http://localhost:3000/',
stats: {
colors: true
}
}))
app.use(webpackHotMiddleware(compiler))
} else {
console.log('server運轉在臨盆環境')
webpack(webpackConfig, function(err, stats) {
if (err) throw err
//輸出打包信息(這裏又能夠用了)
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
app.use(express.static(path.resolve(__dirname, './dist')))
})
}
app.listen(config.port, function() {
console.log('App is now running on port 3000!');
})
運轉之前先裝下swig插件,同時修正下index.html,手寫
//index.html
<script type="text/javascript" src="main.js"></script>
到目前為止的目次構造:
環境搭建完成了,營業代碼及後端邏輯下篇再講;
《手動搭建vue+node單頁面(二)》
https://segmentfault.com/a/11…