一、初始化webpack
(文件名不能有中文字符、大写字母,否则会报错)貌似是这样的npm init -y
npm i webpack webpack-cli -S
1-1 新建webpack.config.js
1-2 修改package.json文件
"build":"webpack --config webpack.config.js"
1-3 初次打包
在根目录下新建src文件夹/index.js文件
在webpack.config.js文件中键入
const path = require('path');
const config = {
entry:path.join(__dirname,'src/index.js'),// 在根目录下新建src文件夹/index.js文件
output:{
/* 打包的文件名 */
filename:"bundle.js",
/* 打包文件的输出目录 */
path:path.join(__dirname,'dist')
},
mode:"development"
}
module.exports = config;
二、配置plugins
npm i html-webpack-plugin -S
npm i clean-webpack-plugin -S
在webpack.config.js中键入 写在const config={}里面
html-webpack-plugin
//在dist目录下自动生成html,让打包的js文件自动插入
const HtmlWebpackPlugin = require('html-webpack-plugin');
plugins:[
...
new HtmlWebpackPlugin({
title:"webpack测试"
})
]
clean-webpack-plugin
//每次打包之前会将dist目录下的文件清除
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
plugins:[
new CleanWebpackPlugin()
]
三、webpack-server
//写代码的时候就可以看到效果npm i webpack-dev-server -S
npm i cross-env -S
3-1 配置package.json
"scripts": {
"build": "cross-env NODE_ENV=production webpack --config webpack.config.js",
"serve":"cross-env NODE_ENV=development webpack-dev-server --config webpack.config.js"
}
3-2 配置webpack.config.js
is(isDev)写在const config={}后面 中间不能加逗号分隔!
const isDev = process.env.NODE_ENV == 'development'
if(isDev){
config.devServer ={
host:'localhost',
port:8080,
/* 错误是否显示在界面上 */
overlay:{
errors:true
},
/* 是否进行热更新 */
hot:true
}
}
四、loader
//处理.vue .css .png|jpgnpm i css-loader style-loader -S
npm i vue-loader vue vue-template-compiler -S
npm i file-loader -S
4-1 配置webpack.config.js
const {VueLoaderPlugin} = require('vue-loader');
const config = {
plugins:[
new VueLoaderPlugin()
],
module:{
rules:[
{
test:/\.css$/,
use:[
'style-loader',
'css-loader'
]
},
{
test:/\.vue$/,
use:'vue-loader'
},
{
test:/\.png|jpg|gif$/i,
use:'file-loader'
}
]
},
mode:"development"
}
4-2 配置src/index.js
根目录下新建一个assets文件夹,index.css文件
在src文件夹里新建一个App.vue文件
import Vue from 'vue'
import '../assets/index.css';
import App from './App.vue';
const root = document.createElement("div");
document.body.append(root)
new Vue({
render:h=>h(App)
}).$mount(root)
npm run serve //查看效果
五、请求网络数据
//App.vuenpm i axios -S
<template>
<div class="container">
<div class="item" v-for="item of musics" :key="item.id"> // 结构渲染数据
<img :src="item.coverUrl" class="pic" alt="">
<p>{{item.name}}</p>
<p>{{item.radio.category}}</p>
</div>
</div>
</template>
<script>
import axios from 'axios' //引入axios
export default {
name: "App",
data(){
return {
musics:[]
}
},
mounted() {
var url = "http://192.168.14.49:3000/top/playlist?cat=日语";
axios.get(url).then(res=>{
this.musics = res.data.playlists
})
}
};
</script>
<style scoped>
.container{
width: 1000px;
margin-right: auto;
margin-left: auto; //css样式
}
.item p:last-child{
color: gray;
display: inline-block;
border: 1px solid gray;
margin-left: 80px;
height: 25px;
font-size: 15px;
}
.item p:nth-of-type(1){
width: 250px;
margin-left: 10px;
}
</style>