以前一直覺得webpack難搞,也想着自己能不使用cli搭一個vue的項目,在入門webpack后成功打開過一個html頁面,但對於vue項目搭建還是一臉懵,今天終於配成功了,總結一下
先記錄一下所需要的依賴和對應版本(講真webpack一個版本一個樣,各依賴不對應都沒法用的)

大概創建的文件有

.....................................................................................................................................................................................................................................................................................
接下來正式進入正題:
1. npm init 創建package.json文件
2. npm install ... 安裝相關的依賴
webpack vue 這個應該不用多說
css-loader style-loader webpack識別css代碼
vue-loader vue-template-compiler webpack識別vue代碼 (沒有這個就和webpack打包普通的html步驟一樣了)
html-webpack-plugin 生成HTML文件的模板
webpack-dev-server 本地服務器運行代碼用的
<template>
<div class="color">{{text}}</div>
</template>
<script>
export default {
data () {
return {
text: 'vue項目成功運行了'
}
}
}
</script>
<style scoped>
.color{
color: red;
}
</style>
4. 創建webpack.config.js文件,配置出入口
const path = require('path')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const config = {
entry: './index.js', // 打包入口,從這個地方開始找文件
output: { // 打包出口,生成disk文件夾
path: path.resolve(__dirname, "disk"),
filename: 'bundle[hash].js'
},
// 上面是打包js用的,下面是解析其他文件用的
module: {
rules: [
{test: /\.css$/, use: ['style-loader', 'css-loader']}, // 解析css文件
{//通過vue-loader來識別以vue結尾的文件
test: /.vue$/, // 解析vue文件
loader: 'vue-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({ // 生成html模板,顯示在頁面(必須,缺少則顯示的是對應的目錄)
template: './index.html'
}),
new VueLoaderPlugin() // 配合vue-loader解析vue文件
]
}
module.exports = config
5. 創建index.js文件,作用是把app.vue渲染到html中
import Vue from 'vue' import App from './app.vue' new Vue({ el: '#app', render: h => h(App) })
6. package.json在script中添加命令
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack --config webpack.config.js", "dev": "webpack serve --config webpack.config.js" },
npm run build 對應上面那個build 執行webpack進行打包
npm run dev 對應上面dev,運行本地服務器運行項目(在之前版本運行命令是:webpack-dev-server --config webpack.config.js)
然后運行就可以了... ...
參考鏈接:
https://blog.csdn.net/fang_ze_zhang/article/details/105436507