webpack 安装与使用
安装:
webpack
webpack-cli 命令工具
npm install webpack webpack-cli --save-dev
执行: 以下命令查看是否安装成功
./node_modules/.bin/webpack -v ./node_modules/.bin/webpack-cli -v
简单的案例开始
目录结构

webpack 构建
默认读取 webpack.config.js 的配置文件
const path = require('path');
module.exports = {
entry: './src/index.js',//入口文件
output: {
filename: 'main.js',//编译出来的文件名
path: path.resolve(__dirname, 'dist')//编译到的目标路径
}
};
webpack 命令介绍
webpack --watch //命令当文件发生变化时自动监听编译 //开启生成环境shortcut for --optimize-minimize --define //process.env.node_env="production" webpack -p webpack --congif //指定文件配置 webpack --progress //输出构建过程
webpack 插件介绍
//清除文件夹插件
const htmlwebpackplugin = require('html-webpack-plugin');
//模板插件
const cleanwebpackplugin = require('clean-webpack-plugin');
//js压缩插件
const uglifyjsplugin = require('uglifyjs-webpack-plugin');
webpack.config.js基本配置
const path = require('path');
//处理模板html自动引入js
const htmlwebpackplugin = require('html-webpack-plugin');
//清除文件夹
const cleanwebpackplugin = require('clean-webpack-plugin');
//js压缩插件
const uglifyjsplugin = require('uglifyjs-webpack-plugin');
const webpack = require('webpack');
module.exports = {
mode:"production",
entry: {
app:'./src/index.js'
},
output: {
filename: '[name].bundle.js',//名字已入口entry 名字命名
path: path.resolve(__dirname, 'dist')//输出文件的路径
},
//输出源码
devtool: 'inline-source-map',
/**
* 一些优化配置
*/
optimization:{
//压缩js
minimizer: [
new uglifyjsplugin()
],
//抽离公用的js部分
splitchunks:{
chunks:'all'
}
},
plugins:[
//清除文件
new cleanwebpackplugin(['dist']),
//设置默认环境变量
new webpack.defineplugin({
'process.env.node_env': '"production"',
local_root: json.stringify("https://ziksang.com")
}),
//模板插件
new htmlwebpackplugin({
title: 'output management'
}),
//配合devserver 实现热更新
new webpack.hotmodulereplacementplugin()
]
};
webpack-dev-server 配置webpack 服务配置
const webpackdevserver = require('webpack-dev-server');
const webpack = require('webpack');
const config = require('./webpack.config.js');
const options = {
contentbase: './dist',//配置根路径
hot: true,//是否开启热更新
host: 'localhost'
};
webpackdevserver.adddevserverentrypoints(config, options);
const compiler = webpack(config);
const server = new webpackdevserver(compiler, options);
//启动端口
server.listen(5000, 'localhost', () => {
console.log('dev server listening on port 5000');
});
package.json
{
"name": "webpack-skeleton",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"error: no test specified\" && exit 1",
"build": "webpack -p --progress",
"watch": "webpack --watch --mode=production",
"start": "webpack-dev-server --open --mode=production",
"devserver": "node dev-server.js"
},
"author": "",
"license": "isc",
"devdependencies": {
"clean-webpack-plugin": "^0.1.19",
"html-webpack-plugin": "^3.2.0",
"uglifyjs-webpack-plugin": "^2.0.1",
"webpack": "^4.21.0",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.9"
}
}
烽火戏母猴