webpack打包less文件
less模块打包需要使用【less-loader】。
参考资料:https://www.webpackjs.com/loaders/less-loader/
webpack打包图片文件
处理图片资源需要【url-loader】和【file-loader】。
【url-loader】配置如下。
// webpack.config.js文件
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8192 // 表示该字节以下的图片用base64编码,超过这个大小的则使用file-loader处理。
}
}
]
}图片模块化打包后,文件会集中在dist目录中,此时如果index.html在根目录,则路径需要调整。可以在webpack.config.js中配置公共路径dist。
//webpack.config.js
output:{
path:path.resolve(__dirname, 'dist'),
filename:'bundle.js',
publicPath: 'dist/'
},图片打包时还可以存放到指定路径并命名。
//webpack.config.js
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
name: 'img/[name].[hash:8].[ext]' //:8表示保留8位
}
}
]
}
webpack将ES6转换为ES5打包
需要使用【babel-loader】、【babel-core】和【babel-preset-es2015】(babel-preset-es2015是配置文件,根据不同转换进行替换)。
安装后配置webpack.config.js文件,使js支持es6转为es5。
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015']
}
}
}
]
}
webpack模块化打包vue代码
npm安装vue:【npm install vue --save】
在js代码中引入Vue:【import Vue from 'vue'】
import Vue from 'vue'
const app = new Vue({
el:"#app",
data:{
message:'hello!2021!'
}
})配置vue别名:webpack.config.js配置resolve,添加alias指向vue/dist/vue.esm.js(使用runtime-compiler,不使用runtime-only)
const path = require('path');
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
resolve:{
alias:{
'vue$': 'vue/dist/vue.esm.js'
}
}
};runtime-only:代码中,不可以有任何template。
runtime-compiler:代码中,可以有template,compiler可以用于编译template。
此时打包后,vue.js代码可以正常解析。
webpack模块化打包vue文件
Vue中el和template属性的关系:template的内容会自动替换el的内容。
Vue通常会将.vue的文件以组件形式引入。如下。
<template>
<div>
<li>heheli>
<li>hahali>
div>
template>
<script>export default{name: "App",
data(){return {message:'hello!2021!'
}
}
}script>
<style>style>// main.js文件
import Vue from 'vue'
import App from '../vue/index.vue'
new Vue({
el:"#app",
template:'',
components:{
App
}
})此时如果需要模块化打包.vue文件,则需要:vue-loader(vue-loader的14版本以上,需要另外配置插件)和vue-template-compiler。
npm install --save-dev vue-loader@13.0.0 vue-template-compiler
修改webpack.config.js文件,添加vue-loader的module。
{
test:/\.vue$/,
use:['vue-loader']
}