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
npm init
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 [email protected]```
package.json
```json
"devDependencies": {
"webpack": "^3.6.0"
}
在终端中的命令都是全局的,所以npm run 脚本,优先执行本地的
main.js引入css
require("./css/normal.css")
webpack官网
vue官网
npm install --save-dev [email protected]
配置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
module: {
rules: [
{
test: /\.css$/,
//css-loader只负责加载,不负责解析--!
//从右向左加载
use: [ 'style-loader', 'css-loader' ]
}
]
}
npm install --save-dev [email protected]
special.less
@fontSize: 50px;
@fontColor: orange;
body{
font-size: @fontSize;
color: @fontColor;
}
main.js引入
require("./css/special.less")
less-loader
cnpm install --save-dev [email protected] [email protected]
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 [email protected]
配置, 64k
{
test: /\.(png|jpg|gif|jpeg)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 65536
}
}
]
}
当加载图片大小< limt时, 转换成base64
当加载图片大小> limt时,需要使用file-loader,将图片重新打包
cnpm install --save-dev [email protected]
文件路径不对,修改配置
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语法处理
es6转换成es5
cnpm install --save-dev [email protected] [email protected] [email protected]
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015']
}
}
}
比如const->var