webpack开发者模式的兼容处理
与生产者模式百分八十都相同
开发者模式在package,json下面的scripts下面添加
开发模式
大多数的配置都是差不多的,只有少部分的配置是不一样的
- 关于CSS的配置,它不需要进行分离了,直接使用 style-loader 插入到页面的 style 标签中去
- 关于图片与字体,它不用再做limit的限制了,它全部转base64直接展示
- 它需要使用 webpack-dev-server 来启动一个服务器调试页面
- 它可以配置热模块替换
"dev": "webpack-dev-server --config ./webpack.config.dev.js"
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config ./webpack.config.js",
"dev": "webpack-dev-server --config ./webpack.config.dev.js"
},
//首先要导入一个包
yarn add webpack-dev-server --dev
//开发者模式下面的webpack配置
const path = require("path");
const HtmlWebpackPlugin=require("html-webpack-plugin");
const {CleanWebpackPlugin}=require("clean-webpack-plugin");
const ProgressBarWebpackPlugin=require("progress-bar-webpack-plugin")
const chalk=require("chalk");
//导入webpack插件,配置热模块替换
const webpack=require("webpack");
const config = {
mode: "development",
entry: path.join(__dirname, "./js/Student.js"),
output: {
filename: "bundle.js",
path: path.join(__dirname, "./dist")
//这里不能配publicPath,开发者模式不允许配置这个
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}, {
test: /\.css$/,
use: [
//在开发者模式下面,是不需要进行css样式分离的,所以不用调用分离的插件
//而直接应该插入在style标签中
"style-loader",
{
loader: "css-loader",
options: {
importLoaders: 1
}
},
"postcss-loader"
]
}, {
test: /\.s(c|a)ss$/,
use: [
//在开发者模式下面,是不需要进行css样式分离的,所以不用调用分离的插件
//而直接应该插入在style标签中
"style-loader",
{
loader: "css-loader",
options: {
importLoaders: 1
}
},
"postcss-loader",
"sass-loader"
]
}, {
test: /\.(jpe?g|gif|png|bmp|svg|ico|tif)$/,
use: [
//在开发者模式下面,不需要考虑是否转换成文件或base64,全部调用base64
"url-loader"
]
},{
//解析bootstrap的字体
test: /\.(ttf|eot|woff|woff2)$/,
use: ["url-loader"]
}
]
},
plugins: [
//清理内容插件
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
filename:"index.html",
template:path.join(__dirname,"./index.html"),
inject:true
}),
new ProgressBarWebpackPlugin({
format:chalk.green("进度:")+chalk.red("[:bar]")+chalk.green(" :percent")+chalk.red(" :plapsed seconds"), //(:elapsed seconds)耗得时间 percent百分比 [:bar]进度条
clear: false //不清除进度条
}),
//根据名称进行模块替换
new webpack.NamedModulesPlugin(),
//热模块替换插件
new webpack.HotModuleReplacementPlugin(),
//配置全局别名
new webpack.ProvidePlugin({
"jquery":"jquery",
"$":"jquery",
"jQuery":"jquery"
}),
],
//配置服务器webpack-dev-server
devServer:{
port:9999, //端口号
contentBase:"./dist", //生成的文件放在dist文件下面
//配置成功以后直接打开浏览器
open:true,
// 开启热模块替换
hot:true
}
}
module.exports = config;
热模块替换
先导入webpack
在配置服务器里面加个hot:true
在插件里面添加
//根据名称进行模块替换
new webpack.NamedModulesPlugin(),
//热模块替换插件
new webpack.HotModuleReplacementPlugin(),
配置全局别名
new webpack.ProvidePlugin({
"jquery":"jquery",
"$":"jquery",
"jQuery":"jquery"
}),
当配置完上面的东西以后,我们就可以直接使用jQuery以及jQuery的第三方插件了
import $ from "jquery"; // 根据bootstrap的package.json配置,导入的是dist/js/npm.js
import "bootstrap";
import "bootstrap/dist/css/bootstrap.css";