webpack.config.js
let path = require("path");
let HtmlWebpackPlugin = require("html-webpack-plugin"); // js与页面产生关联
let MiniCssExtractPlugin = require("mini-css-extract-plugin"); // 打包css使之独立出来,并被html引用
// env 是内置参数 可以反应当前运行的环境
module.exports = (env) => {
return {
mode: env, // 开发(此环境不压缩代码) 或者 正式环境
entry: ["babel-polyfill", "./index.js"], //es6 转 es5 入口文件(从哪里开始)
output: {
filename: "./js/bundle.js", // 加文件路径会自动创建文件夹
path: path.resolve(__dirname, "dist"), // 出口文件夹名
libraryTarget: "window", // 如果设置为window export的变量可以用在script标签引入并正常读取
},
devtool: "source-map", // 开发环境更好观察打包的代码
module: {
rules: [
{
test: /\.js$/, // 检测以js结尾的文件
exclude: /node_modules/, // 除了此文件夹以外的文件
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
cacheDirectory: true, // 打包时优先利用缓存 提升打包效率
plugins: [
[
"@babel/plugin-proposal-class-properties", // class处理
{
loose: true,
},
],
],
},
},
},
{
test: /\.(c|le|sc)ss/, // 检测css less scss文件
use: [
{
loader: MiniCssExtractPlugin.loader, // 把引入的css放入css文件夹 link标签引入 不会直接进入页面style
},
"css-loader",
{
loader: "postcss-loader",
options: {
plugins: [require("autoprefixer")("last 10 versions")], // 解决css浏览器兼容性
},
},
"sass-loader",
],
},
{
test: /\.(png|jpg|gif|svg|jpeg)$/, // 检测图片的类型
use: {
loader: "url-loader", // 如果设置limit 会对小于该数值的图片进行base64位的转换 如果大于则直接拷贝
options: {
publicPath: "../images", // 打包图片的存放路径 如果不加../ 会有问题
outputPath: "images", // 打包存放图片的文件夹名
limit: 30 * 1024, // 以此数值进行划分是否转换base64
name: "[name].[ext]", // 以图片原有名保存,不配置则是随机码命名
},
},
},
],
},
plugins: [
new HtmlWebpackPlugin({
// 打包后的js与html文件的关系配置
title: "测试", // 打包后html title的文案
filename: "index.html", // 打包后的html文件名
inject: "head", // 打包后script 标签放在head里面
minify: {
removeComments: false, // 是否删除换行
collapseWhitespace: false, // 是否删除空格
},
template: "index.html", // 配置后使用当前html作为模版来渲染
}),
new MiniCssExtractPlugin({
// 存放打包后css的路径
filename: "./css/index.css",
}),
],
};
};
package.json
{
"name": "webpack3",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "rimraf dist && webpack --env=production",
"build:dev": "rimraf dist && webpack --env=development",
"build:prd": "rimraf dist && webpack --env=production"
},
"author": "",
"license": "ISC",
"dependencies": {
"@babel/plugin-proposal-class-properties": "^7.8.3",
"babel-polyfill": "^6.26.0",
"rimraf": "^3.0.2",
"webpack": "^4.41.2"
},
"devDependencies": {
"@babel/cli": "^7.6.4",
"@babel/core": "^7.6.4",
"@babel/preset-env": "^7.6.3",
"@babel/preset-react": "^7.6.3",
"autoprefixer": "^9.7.1",
"babel-loader": "^8.0.6",
"css-loader": "^3.2.0",
"file-loader": "^4.2.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "^4.13.0",
"postcss-loader": "^3.0.0",
"sass-loader": "^8.0.0",
"style-loader": "^1.0.0",
"url-loader": "^2.2.0",
"webpack-cli": "^3.3.10"
}
}