使用时、只需要在html中正常引用图片即可、webpack就会找到对应的资源进行打包、并修改html中的引用路径
主要是将html中的img路径文件进行打包、和copy-webpack-plugin是有区别的、copy-webpack-plugin主要是拷贝一些资源文件
项目中的图片资源都使用html-withimg-loader
项目中的音频、视频等资源文件使用copy-webpack-plugin
安装
npm i -S html-withimg-loader
配置 loader
{
test:/\.(htm|html)$/,
loader: 'html-withimg-loader'
}
虽然SPA大行其道、但是多页应用还是非常重要的
修改配置文件
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或require
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)
原文:https://www.cnblogs.com/nordon-wang/p/11252994.html