持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第17天,点击查看活动详情
处理字体
- css
// 声明字体
@font-face {
font-family: "webfont";
font-display: swap;
src: url("../font/webfont.woff2") format("woff2");
}
// 使用字体
body{
font-family: 'webfont' !important;
div {
display: flex;
height: 100px;
background: url(../images/img.jpg) 0 0 no-repeat; // 1.2 css中的图片
}
}
- webpack.config.js
{
test: /\.(eot|woff|woff2|wvg|ttf)$/,
use: {
loader: 'file-loader',
// loader: 'url-loader',
options: {
name: '[name].[ext]',
outputPath: 'font',
publicPath: '../font'
}
}
}
多页面打包通用解决方案
多页面打包通用解决方案:
- 新建一个多页面打包的配置文件mpa.config.js,然后在package.json增加一条命令,让进行多页面打包的时候执行该条命令
- 复制webpack.config.js中的内容到新建配置文件mpa.config.js中,然后进行修改。在配置文件中需要做好一个约定:
所有页面入口模块和相应的html模块都要放在一个目录下
步骤: 定义一个函数setMPA, 走配置之前,走下这个函数:生成entry,实例化htmlwebpackPlugin
- 查询页面入口模块 路径 以及相应html模块
- 提取页面入口的名称,用于entry的chunkName
- 赋值entry, 将htmlwebpackPlugin解构放到插件配置中
- package.json:增加一条命令
"scripts": {
"mpa": "webpack --config ./mpa.config.js"
},
- 复制webpack.config.js中的内容到新建配置文件mpa.config.js中
需要安装glob:
npm install glob -D
// webpack的配置文件
const { resolve, join } = require("path")
const glob = require("glob")
const htmlwebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin")
const miniCssPlugin = require("mini-css-extract-plugin")
// 走配置之前,走下这个函数:生成entry,实例化htmlwebpackPlugin
const setMPA = () => {
const entry = {}
const htmlwebpackPlugins = []
// 查询页面入口模块 路径 以及相应html模块
// 提取页面入口的名称,用于entry的chunkName
// 约定:所有页面入口模块和相应的html模块都要放在一个目录下
const entryPath = glob.sync(join(__dirname, "./src/*/index.js"))
// console.log(entryPath)
entryPath.map((item, index) => {
const entryName = item.match(/src\/(.*)\/index\.js$/)[1]
entry[entryName] = item
htmlwebpackPlugins.push(
new htmlwebpackPlugin({
template: join(__dirname, `./src/${entryName}/index.html`), // `./src/${entryName}/index.html`,
filename: `${entryName}.html`,
chunks: [entryName]
})
);
})
console.log('entry', entry);
console.log('htmlwebpackPlugins', htmlwebpackPlugins);
return {
entry,
htmlwebpackPlugins
}
}
const { entry, htmlwebpackPlugins } = setMPA()
// webpack是基于nodeJS
// 原理就是通过shell脚本在node_modules/.bin⽬录下创建⼀个软链接
module.exports = {
entry,
output: {
// 生成的资源存放的位置, 必须是绝对路径
path: resolve(__dirname, './mpa') ,
// 生成的资源文件名
// filename: 'index.js' // 占位符 [name]
filename: 'js/[name][chunkhash:8].js' // 占位符 [name],⽂件名称不要重复
},
mode: "development", // none(既无开发体验,也无优化) development(开发体验) production(优化)
// 7. 如何处理路径问题: 解决了问题7
resolveLoader: {
modules: ["./node_modules", "./myLoaders"]
},
module: {
rules: [
.
.
.
]
},
plugins: [
new CleanWebpackPlugin(), // 目录清理
...htmlwebpackPlugins,
new miniCssPlugin({
filename: "style/index.css"
}), // 样式抽取成独立的文件
],
}