使用时、只须要在html中正常引用图片便可、webpack就会找到对应的资源进行打包、并修改html中的引用路径html
主要是将html中的img路径文件进行打包、和copy-webpack-plugin是有区别的、copy-webpack-plugin主要是拷贝一些资源文件jquery
项目中的图片资源都使用html-withimg-loaderwebpack
项目中的音频、视频等资源文件使用copy-webpack-pluginweb
安装npm
npm i -S html-withimg-loader
复制代码
配置 loaderjson
{
test:/\.(htm|html)$/,
loader: 'html-withimg-loader'
}
复制代码
虽然SPA大行其道、可是多页应用仍是很是重要的bash
修改配置文件闭包
entry:{
index: './src/index.js',
other: './src/other.js'
},
output: {
path: path.join(__dirname, 'dist'),
// filename:'bundle.js',
filename:'[name].js',
publicPath: '/'
},
plugins:[
// new HtmlWebpackPlugin({
// filename: 'index.html',
// template: './src/index.html'
// }),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html',
chunks:['index']
}),
new HtmlWebpackPlugin({
filename: 'other.html',
template: './src/other.html',
chunks:['other']
})
],
复制代码
能够经过 expose-loader 进行全局变量的注入、同时也可使用内置插件 webpack.ProvidePlugin 对每一个模块的闭包空间注入一个变量,自动加载模块,而没必要处处import或requireide
expose-loader优化
将库引入到全局做用域
安装
npm i -D expose-loader
复制代码
配置loader
module:{
rules:[
{
test: require.resolve('jquery'),
use:{
loader: 'expose-loader',
options: '$'
}
}
]
}
复制代码
require.resolve 用来获取模块的绝对路径、因此这里的loader只会做用于jq模块而且只有在bundle中使用它时才会进行处理
webpack.ProvidePlugin
将库自动加载到每一个模块
引入webpack
const webpack = require('webpack')
复制代码
配置
plugins:[
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
复制代码
项目开发时通常须要使用两套配置文件、用于开发阶段打包(不压缩代码、不优化代码增长效率)和上线阶段打包(压缩代码、优化代码,打包后直接上线使用)
须要安装 webpack-merge
npm i -D webpack-merge
复制代码
抽取三个配置文件
实现步骤
webpack配置的路径问题
Webpack 配置时,相对路径都是相对于根目录的,绝对路径就是配置文件所处的文件目录,所以在将配置文件放置的不是在根目录的时候,须要注意绝对路径是否以根目录为参照的
除了区分不一样的配置文件进行打包、还须要在开发时知道当前的环境时开发阶段仍是上线阶段、因此能够借助内置插件
DefinePlugin
来定义环境变量、最终能够实现开发阶段和上线阶段的区分
引入webpack
const webpack = require('webpack')
复制代码
建立插件对象并定义环境变量
须要注意 DefinePlugin 设置的值是一个表达式,
IS_DEV: 'true'是设置IS_DEV为boolean类型的true
number: '1 + 1'是设置number为2,由于是一个表达式,因此'1 + 1'会进行运算将获得的值赋值给健string: '"设置字符串的值"',设置字符串的值须要多嵌套一层引号
variables: 'textVar'表明的是将textVar变量的值设置给variables,而不是将textVar做为字符串赋值给variables
plugins:[
new webpack.DefinePlugin({
IS_DEV: 'true',
number: '1 + 1',
string: '"设置字符串的值"',
variables: 'textVar'
})
]
复制代码
在src打包的代码环境下能够直接使用
console.log('我是index js', IS_DEV, number, string)
复制代码