安装完nodejs之后,需要安装全局webpack
npm install webpack -g
npm install webpack-cli -g
math.js
function add(a,b) {
return a+b;
}
function sub(a,b) {
return a-b;
}
module.exports = {
add,
sub
}
main.js
//commonJS语法
const{add,sub} = require("./math")
var a = 10,b = 5;
var t1 = add(a,b);
console.log(t1);
//ES6语法
import {name,age,sex} from './info'
console.log(name);
使用的是commonJS语法,html无法引入,需要webpack进行打包。
webpack ./src/main.js -o ./dist/bundle.js
webpack.config.js
npm init
生成package.json文件
npm install
const path = require('path')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname,'dist'),
filename: 'bundle.js'
}
}
使用webpack命令,即可对文件进行打包处理,webpack命令就不需要写这么长了!
将webpack命令进行映射!=> npm run build
在package.json文件中进行更改
{
"name": "meetwebpack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"author": "kcl",
"license": "ISC"
}
不同的项目webpack版本可能不一样,每个项目需要导入自己的webpack版本依赖
cnpm install webpack@3.6.0```
package.json
```json
"devDependencies": {
"webpack": "^3.6.0"
}
在终端中的命令都是全局的,所以npm run 脚本,优先执行本地的
在webpack loader
main.js引入css
require("./css/normal.css")
npm install --save-dev css-loader@2.0.2
配置webpack.config.js
const path = require('path')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname,'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [ 'css-loader' ]
}
]
}
}
再进行打包
npm run build
style-loader
module: {
rules: [
{
test: /\.css$/,
//css-loader只负责加载,不负责解析--!
//从右向左加载
use: [ 'style-loader', 'css-loader' ]
}
]
}
npm install --save-dev style-loader@0.23.1
less打包
special.less
@fontSize: 50px;
@fontColor: orange;
body{
font-size: @fontSize;
color: @fontColor;
}
main.js引入
require("./css/special.less")
less-loader
cnpm install --save-dev less-loader@4.1.0 less@3.9.0
module: {
rules: [
{
test: /\.css$/,
//css-loader只负责加载,不负责解析--!
use: [ 'style-loader', 'css-loader']
},{
test: /\.less$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "less-loader" // compiles Less to CSS
}]
}
]
}
图片文件处理
url-loader
cnpm install --save-dev url-loader@1.1.2
配置, 64k
{
test: /\.(png|jpg|gif|jpeg)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 65536
}
}
]
}
当加载图片大小< limt时, 转换成base64
当加载图片大小> limt时,需要使用file-loader,将图片重新打包
cnpm install --save-dev file-loader@3.0.1
文件路径不对,修改配置
output: {
path: path.resolve(__dirname,'dist'),
filename: 'bundle.js',
publicPath: 'dist/'
},
为了便于管理图片文件,不让图片放在同一个报下,以及图片名称不好管理,现在需要重新配置fileloader
{
test: /\.(png|jpg|gif|jpeg)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 1024,
name: 'img/[name].[hash:8].[ext]'
},
}
]
}
ES6转ES5 babel
ES6语法处理
es6转换成es5
cnpm install --save-dev babel-loader@7.1.5 babel-core@6.26.3 babel-preset-es2015@6.24.1
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015']
}
}
}
比如const->var