一、用webpack打包
新建一个文件夹 webpack-demo
1. 初始化 npm 执行命令
$ npm init (只生成一个package.json文件)
2.安装webpack
$ npm install webpack --save-dev (生成node_modules文件夹)
3. 在webpack-demo下面新建一个hello.js文件
function hello(str){
alert(str);
}
4. 用webpack打包
1) $ webpack hello.js hello.bundle.js
解决webpack can't find module 'webpack-cli' 一系列报错
https://blog.csdn.net/lplife/article/details/80650993
2)package.json.添加上"dev"和"build"这两个信息以及他们的值.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack --mode development",
"build": "webpack --mode production"
},
npm run dev (开发环境输出的demo.js没有压缩),
npm run build (生产模式输出的demo.js压缩过)
3)全局安装 webpack-cli
$ npm install --save-dev webpack-cli -g
4) 安装完成后, 输入命令 npm run dev (继续报错)
我们先创建src文件.还有一个dist文件,存放默认的打包生成的文件, 然后在src里再创建index.js文件
$ webpack hello.js -o hello.bundle.js(还是有黄色警告)
5)更换打包命令
$ npx webpack ./hello.js -o hello.bundle.js --mode development (4.0以上要用npx)
6) 新建 world.js
function world(){
return {
}
}
在hello.js里引用 world.js 打包
require("./world"),
7)新建 style.css
在hello.js里引用
require("style-loader!css-loader!./style.css")
为了不需要引入的每一个都写上style-loader和css-loader 打包命令里加上
打包style和css 如下命令
$ npx webpack ./hello.js -o hello.bundle.js --module-bind 'css=style-loader!css-loader' --watch
8) 查看打包进程
npx webpack ./hello.js -o hello.bundle.js --module-bind 'css=style-loader!css-loader' --progress
查看打包模块
npx webpack ./hello.js -o hello.bundle.js --module-bind 'css=style-loader!css-loader' --progress --display-modules
配置package.json
$ npm run webpack
运行 npx webpack 报黄色警告
解决方案: 在webpack.config.js 里 与entry平级 加上mode:"none"
二、webpack 参数
1.entry 有3种方式
1)字符串 单个文件
2)数组
entry: ['./src/script/main.js','./src/script/a.js'] ,
3)对象 filename也要对应改变 [name].js
如果指定chunkhash 假如修改了文件 2次打包的hash值会不一样
三、自动化生成项目中的HTML页面
1安装HTML插件
$ npm install html-webpack-plugin --save-dev
2.在webpack.config.js中 引用插件
3.运行下 $ npm run webpack
在dist文件夹下面生成了index.html文件 并自动引用了 2个打包的文件
4.想要dist里面的html与根目录下的html发生关联
在webpack.config.js里
plugins:[
new htmlWebpackPlugin({
template:"index.html" //指向根目录下的html
})
重新打包 npm run webpack
dist里面的index.html 自动引入根目录下的index.html里的文件
5.dist下面的文件分类
dist下面的目录 js会自己创建一一个文件夹并且放js里面
6.设置plugin里面的参数
1)hash
$ npm run webpack dist文件下带hash的index.html 结果如下
2)title参数
在webpack.config.js的plugin里设置title参数
title:"webpack is good"
在根目录下的index.html的title里用<%=%>
<title><%= htmlWebpackPlugin.options.title%></title>
$ npm run webpack dist文件下index
3)date参数
4)htmlWebpackPlugin 里面的 options
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="./dist/bundle.js"></script>
<title><%= htmlWebpackPlugin.options.title%></title>
</head>
<body>
<!-- 循环遍历htmlWebpackPlugin -->
<%= htmlWebpackPlugin.options.date %>
<% for(var k in htmlWebpackPlugin) { %>
<%= k %>
<% } %>
</body>
</html>
结果如下:
5) htmlWebpackPlugin 里面的 files
结果如下
option和files
<body>
<!-- 循环遍历htmlWebpackPlugin的files -->
<% for(var k in htmlWebpackPlugin.files) { %>
<%= k %> <%= JSON.stringify(htmlWebpackPlugin.files[k]) %>
<% } %>
<!-- 循环遍历htmlWebpackPlugin的options -->
<% for(var k in htmlWebpackPlugin.options) { %>
<%= k %> <%= JSON.stringify(htmlWebpackPlugin.files[k]) %>
<% } %>
</body>
结果如下:
<!-- 循环遍历htmlWebpackPlugin的files -->
publicPath ""
chunks {"main":{"size":56,"entry":"js/main.js","hash":"a66f9e5e909bf091064a","css":[]},"a":{"size":57,"entry":"js/a.js","hash":"154601132c358ad20238","css":[]}}
js ["js/main.js","js/a.js"]
css []
manifest
<!-- 循环遍历htmlWebpackPlugin的options -->
template: "F:\\study\\vue2.0shop\\code\\webpack-demo\\node_modules\\html-webpack-plugin\\lib\\loader.js!F:\\study\\vue2.0shop\\code\\webpack-demo\\index.html"
templateParameters:
filename: "index.html"
hash: false
inject: "head"
compile: true
favicon: false
minify: false
cache: true
showErrors: true
chunks: "all"
excludeChunks: []
chunksSortMode: "auto"
meta: {}
title: "webpack is good"
xhtml: false
date: "2019-04-04T01:05:07.849Z"
6) 一部分在头部引用 一部分在body
且把配置里面的inject 设置为false
结果如下
7.上线需要配置参数
output里的publicPath
结果如下: 所有的JS都会带上配置的地址
minify 把生成的文件压缩
在plugins的htmlWebpackPlugin里面设置
minify:{
removeComments:true, //去除注释
collapseWhitespace:true //移除空格
}
结果 压缩成一行了 且注释没了
8、使用html-webpack-plugin插件生成多页面的HTML
在plugin里复制多个htmlWebpackPlugin对象
plugins: [
new htmlWebpackPlugin({
template: "index.html", //指向根目录下的html
//filename:"index-[hash].html",//文件为hash
filename: "a.html",
// inject:"head" ,//引入的文件在head还是body里面
inject: "body",
title: "this is a.html",
chunks: ["main", 'a']
}),
new htmlWebpackPlugin({
template: "index.html", //指向根目录下的html
//filename:"index-[hash].html",//文件为hash
filename: "b.html",
// inject:"head" ,//引入的文件在head还是body里面
inject: "body",
title: "this is b.html",
chunks:['b']
}),
new htmlWebpackPlugin({
template: "index.html", //指向根目录下的html
//filename:"index-[hash].html",//文件为hash
filename: "c.html",
// inject:"head" ,//引入的文件在head还是body里面
inject: "body",
title: "this is c.html",
chunks:['c']
}),
]
在entry 定义入口
entry: {
main: './src/script/main.js',
a: './src/script/a.js',
b: './src/script/b.js',
c: './src/script/c.js',
},
运行后 每个HTML 都会有对应的文件
如dist里面的a.html
报错信息
解决方案:根目录下的template index.html不能引入文件 注释都不能有
9.excludeChunks 除了XX以外的chunk
src里的index的
<%= htmlWebpackPlugin.files.chunks.main.entry.substr(htmlWebpackPlugin.files.publicPath.length) %>
运行后 不带publicPath
<script type="text/html">
<%=compilation.assets[htmlWebpackPlugin.files.chunks.main.entry.substr(htmlWebpackPlugin.files.publicPath.length)].source()%>
</script>
附件:
webpack.confi
g.js
2.18KB
webpack-dem
o.zip
8.37MB
四、处理项目中的资源文件
loader
1.安装loader 三种方式 https://www.webpackjs.com/concepts/loaders/
- 配置(推荐):在 webpack.config.js 文件中指定 loader。
module: { rules: [ { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader', options: { modules: true } } ] } ] }
2.babel-loader 转换ES6代码
安装
npm install -D babel-loader @babel/core @babel/preset-env webpack
在webpack.config.js添加配置
module: {
rules: [
{
test: /\.m?js$/,
include: path.resolve(__dirname,'src'), //只打包src下的文件
exclude: path.resolve(__dirname,'node_modules'), //除去node_modules里的文件
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
在src下面新建app.js webpack.config.js修改打包的入口和输出
entry: './src/app.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'js/[name].bundle.js',
},
3.css-loader
1) 安装 npm install --save-dev style-loader css-loader
src目录下新建css文件夹 新建common.css 写一些公共样式
发布 看 dist下面的index.html背景色变了
2)postcss-loader
npm i -D postcss-loader
npm i -D autoprefixer (自动增加浏览器前缀)
webpack.config.js 的rules 的css加上
use: ['style-loader', 'css-loader','postcss-loader' ],
或者
use: [
'style-loader',
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader'
]
postcss报错
解决方案:
新建一个postcss.config.js
module.exports = {
plugins: {
'autoprefixer': {browsers: 'last 5 version'}
}
}
假如common.css引入flex.css 想要全部css都被加上前缀
options参数里面定义
结果
4.less和sass
安装 npm install less-loader --save-dev
npm i less --save-dev
less-loader报错
解决:因为webpack的顺序加载是从右往左 先是less再postcss.....
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
'less-loader' // compiles Less to CSS
]
}
安装sass
npm install sass-loader --save-dev
webpack.config.js 的rules里增加一个对象
{
test: /\.sass$/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
'sass-loader'
]
}
5.处理模板文件
1.在layer.js里 import layer.html文件
在index.html文件
在app.js
import './css/common.css';
import Layer from './components/layer/layer.js';
const App = function(){
console.log(Layer);
var dom = document.getElementById("app");
var layer = new Layer();
dom.innerHTML = layer.tpl
}
new App();
引入了HTML 直接运行会报错
解决方案:
需要安装 html-loader
npm install html-loader --save-dev
webpack.config.js里需要
{
test: /\.(html)$/,
use: {
loader: 'html-loader',
options: {
attrs: [':data-src']
}
}
},
2.ejs-loader
在layer.html里
<div class="layer">
sdhfk
<div> this is a <%= name %> layer</div>
<%= htmlWebpackPlugin.options.date %>
<% for(var i=0;i<=arr.length;i++) { %>
<%= arr[i] %>
<% } %>
</div>
npm install ejs-loader --save-dev
在webpack.config.js里添加
{
test: /\.ejs$/,
use: {
loader: 'ejs-loader',
}
},
新建一个layer.ejs
<div class="layer">
<div> this is a <%= name %> layer</div>
<% for(var i=0;i<=arr.length;i++) { %>
<%= arr[i] %>
<% } %>
</div>
在layer.js里 导入layer.ejs
在app.js
dist里面的index.html
3. file-loader
安装 npm install file-loader --save-dev
在webpack.config.js
{ test: /\.(png|jpg|gif|svg)$/i, use: [ { loader: 'file-loader', options: {}, }, ], },
src 下新建assets 下面放一张图片
可以在src的index里面引用
也可以在其他的文件引用 用require
4.url-loader
安装
$ npm install url-loader --save-dev
打包 只有index.html 图片变成了base64