webpack其实就是一个打包工具。它能够将各类当下主流的sass,less,tsx,vue,jsx,json甚至png,svg等各类格式的文件转化为浏览器能够识别的html,css,js和图片资源文件。将他们按照各类依赖关系,整合在一块儿,输出到一个bundle文件中。javascript
webpack首先本地建立一个webpack-test文件夹,而后打开命令提示符,进入此目录,执行命令npm init(npm是node.js自带的一个包管理工具,安装node.js就会自动安装npm)。css
用来记录项目操做流程的package文件有了以后,就要进入正题了,若是以前没有退命令行的webpack-test目录的话,执行命令html
npm install --save-dev webpack webpack-cli --registry=https://registry.npm.taobao.org
vue
(--registry=https://registry.npm.taobao.org
)java
这个配置是为了解决国内用户下载npm模块速度慢,以及有时候会下载失败的可能 安装webpack和webpack-cli(这两个插件缺一不可,webpack是打包工具,webpack-cli是处理打包命令的webpack自带的方便用户的脚手架) 执行命令成功以后的效果:node
import './styles.css';
function component() {
var element = document.createElement('div');
var button = document.createElement('button');
var br = document.createElement('br');
console.log(_.join(['Hello1', 'providePlugin'], ' '));
button.innerHTML = 'Click me1 lok at the console!';
element.appendChild(br);
element.appendChild(button);
//懒加载,第一次打开页面的时候不会去加载对应的js资源文件,当触发事件的时候才去加载资源文件
// webpackChunkName 这个注释的做用是命名懒加载的资源文件,不然会按照数字递增命名
button.onclick = e => import(/* webpackChunkName: "math" */ './math').then(module => {
var print = module.default;
print();
});
return element;
}
document.body.appendChild(component());
复制代码
console.log(
'The print.js module has loaded! See the network tab in dev tools...'
);
export function square(x) {
return x * x;
}
export function cube(x) {
return x * x * x;
}
export default () => {
console.log('Button Clicked: Here\'s "some text"!');
}
复制代码
body{
background-color: aquamarine
}
复制代码
目录截图:webpack
接下来咱们经过配置webpack配置文件,而后让index文件里面的内容显示在浏览器上。看到这里,你可能有个疑问:这个目录下面连个html文件都没有,它怎么显示到浏览器上面?假如你看过官网的教程或者其余社区中的一些一步一步的webpac教程,这个文件夹里面一开始确实是有html文件的,可是咱们这里是10分钟快速上手,就省略了,缘由后面的标题会讲。web
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
entry: {
index: './src/index.js'
},
output: {
filename: '[name].[hash].js',
path: path.resolve(__dirname, 'dist'),
// publicPath:'/' //这个路径会用于出口的html文件引入关联文件的路径
},
optimization: {
// 提取公用代码块,优化打包大小必备
splitChunks: {
cacheGroups: {
commons: {
name: "commons",//公用代码块名称
chunks: "initial",
minChunks: 1
}
}
}
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Production'
}),
new webpack.ProvidePlugin({
_: 'lodash' //全局变量整个lodash
// join: ['lodash', 'join'] //全局join 所有用lodash里面的join方法
})
],
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
}
]
}
};
复制代码
const common = require('./webpack.common.js');
const merge = require('webpack-merge');
const webpack=require('webpack');
module.exports =env => {
// Use env.<YOUR VARIABLE> here:
console.log('来了') // 'local'
console.log('Production: ') // true
return merge(common, {
mode:'development',
devtool: 'inline-source-map',//开启这个能够在开发环境中调试代码
devServer: {
contentBase: "./dist",
compress: true,
port: 3000,
hot:true
},
plugins:[
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()//这两个插件用于开发环境时,修改保存代码以后页面自动刷新
]
});
}
复制代码
const common = require('./webpack.common.js');
const merge = require('webpack-merge');
// const UglifyJsPlugin =require('uglifyjs-webpack-plugin');
module.exports = merge(common, {
devtool: 'source-map',//开启这个能够在生产环境中调试代码
// plugins:[
// new UglifyJsPlugin({ //尝试了一下代码压缩,可是会报错尚未找到缘由
// sourceMap: false
// })
// ],
mode:'production'
});
复制代码
"build": "webpack --config webpack.prod.js",
"start": "webpack-dev-server --open --config webpack.dev.js",
复制代码
此时package.json的完整内容是:npm
{
"name": "wbpack-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.prod.js",
"start": "webpack-dev-server --open --config webpack.dev.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.34.0",
"webpack-cli": "^3.3.4"
}
}
复制代码
通过前面这么多的铺垫,终于到了咱们的最主要的打包环节,话很少说,直接开始。json
仍是用命令提示符进入到webpack-test目录,而后运行命令:
npm run build
复制代码
(这个命令会告诉webpack
打包工具去执行package.json
里面的scripts
对象的build
的脚本,也就是说实际执行的是webpack --config webpack.prod.js
) 。
这个命令还有一个问题就是 –config webpack.prod.js
,为什么会有这个选项呢,这是由于webpack打包工具会使用webpack.config.js
这个文件看成默认配置文件,咱们若是不想使用这个默认配置文件,可使用--config
这个配置,更改webpack的配置项文件。
下面是运行效果:
这么一长串东西,一看就是报错,为何会报错呢,是由于代码里面的一些依赖项模块没有安装,因此下面咱们来安装好咱们配置项和代码里面各类依赖。
检查了一下代码和配置项文件,发现缺乏的模块,而后咱们执行脚本安装它们
install --registry=https://registry.npm.taobao.org --save-dev clean-webpack-plugin html-webpack-plugin css-loader file-loader style-loader webpack-merge
上面这段脚本含有-dev
因此会安装到package.json
文件的devDependencies
属性中
而下面这段脚本会安装到dependencies
属性中
install --registry=https://registry.npm.taobao.org --save lodash
安装完以后的package.json
文件如今是这样的:
使用 --save-dev 安装的 插件,被写入到 package.json 文件的devDependencies 域里面去,而使用 --save 安装的插件,则是被写入dependencies 区块里面去。devDependencies 里面的插件只用于开发环境,不用于生产环境,dependencies 是须要发布到生产环境的。
好比咱们写一个项目要依赖于jQuery,没有这个包的依赖运行就会报错,这时候就把这个依赖写入dependencies ;而咱们使用的一些构建工具好比glup、webpack这些只是在开发中使用的包,上线之后就和他们不要紧了,因此将它写入devDependencies。
这时候再运行命令npm run build
能够看到打包成功了,目录下也多出了打包以后的dist文件夹
最后测试效果:
file:///D:/wbpack-test/dist/index.html
复制代码
首先在src文件夹下面新增一个printf.js文件
console.log(
'The print.js module has loaded! See the network tab in dev tools...'
);
复制代码
entry: {
index: './src/index.js',
print:'./src/print.js'
},
output: {
filename: '[name].[hash].js',
path: path.resolve(__dirname, 'dist'),
// publicPath:'/' //这个路径会用于出口的html文件引入关联文件的路劲
},
复制代码
最后运行打包命令:
npm run build
能够看出,print.js也已经输出到dist文件夹了。
clean-webpack-plugin
这个插件用来清除生成目录的缓存文件。
html-webpack-plugin
这个插件用来生成入口html
文件,在这个html里面自动添加依赖。
Webpack-merge
这个是用来合并webpack配置文件的,为何不适用object.assign
呢?由于object.assign
这个不能深拷贝。
Webpack.NameModulesPlugin
和webpack.HotModuleReplacementPlugin
这两个插件一块儿使用于开发环境,修改保存代码以后自动刷新页面