公共配置:
//公共配置
const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
const CopyWebpackPlugin = require("copy-webpack-plugin")
module.exports = {
entry: {
list: "./src/list/index.js",
detail: "./src/detail/index.js"
},
output: {
filename: "scripts/[name].[chunkhash:5].js"
},
resolve: {
alias: {
"@": path.resolve(__dirname, "src") //绝对路径
}
},
stats: {
modules: false,
colors: true
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/list.html",
filename: "list.html",
chunks: ["list"]
}),
new HtmlWebpackPlugin({
template: "./public/detail.html",
filename: "detail.html",
chunks: ["detail"]
}),
new CopyWebpackPlugin([ //把css和img移到dist目录下
{ from: './public', to: './' }
])
]
}
开发环境:
//开发环境
module.exports = {
mode: "development",
devServer: {
open: true,
openPage: "list.html", //默认进入list页面
proxy: {
"/api": {
target: "http://yuanjin.tech:5100/",
changeOrigin: true
}
}
}
}
生产环境:
//生产环境
const { CleanWebpackPlugin } = require("clean-webpack-plugin")
module.exports = {
mode: "production",
plugins: [
new CleanWebpackPlugin(),
]
}
基本配置:
webpack.config:
const baseConfig = require("./webpack.base")
const devConfig = require("./webpack.dev")
const prodConfig = require("./webpack.prod")
module.exports = function (env) {
if (env && env.prod) {
//生产环境
const config = {
...baseConfig, //两个合并一下
...prodConfig
}
config.plugins = [...baseConfig.plugins, ...prodConfig.plugins]
return config;
}
else {
//开发环境
return {
...baseConfig,
...devConfig
}
}
}
areaServicejs:导出两个函数
/**
* 得到所有的省份
*/
export async function getProvinces() {
return await fetch("/api/local").then(resp => resp.json()) //直接解析成json数据
}
/**
* 根据省份id得到所有的城市
*/
export async function getCities(parentId) {
const url = `/api/local?parentId=${parentId}`;
return await fetch(url).then(resp => resp.json())
}
list的indexjs:
import { getProvinces } from "@/util/areaService" //@对应src目录
import $ from "jquery"
/**
* 详情页需要:
* 省份的全称
* 省份的id
*/
getProvinces().then(ps => {
//ps:省份的数组
const ul = $(".provinces");
for (const p of ps) {
const li = $("<li>").appendTo(ul);
const a = $("<a>").text(p.simpleName).appendTo(li);
a.prop("href", `detail.html?name=${p.areaName}&id=${p.id}`)
}
});
detail的index.js:
import { getCities } from "@/util/areaService"
import qs from "query-string"
import $ from "jquery"
const parsed = qs.parse(location.search);
$(".title").text(parsed.name)
const dl = $("dl");
getCities(parsed.id).then(cs=>{
for(const c of cs){
$("<dd>").text(c.simpleName).appendTo(dl)
}
})