1. 关于Webpack
Webpack是一款前端资源加载和打包的工具,能将工程的css、png、js等生成对应的静态资源文件。
2. Webpack安装
npm install webpack -g
npm install webpack-cli -g
查看版本
webpack -v
3. js打包
3.1 新建breeze 目录
mkdir breeze
目录
mkdir src
新建src,在src目录下
3.2 新建bar.js
exports.info=function(str){
document.write(str);
}
3.3 新建foo.js
exports.add=function(a,b){
return a+b;
}
3.4 新建main.js
var bar=require('./bar');
var foo=require('./foo');
bar.info('Hello World!'+foo.add(250,250));
3.5 新建webpack.config.js
在src同级目录新建webpack.config.js
var path=require("path");
module.exports={
entry:'./src/main.js',
output:{
path:path.resolve(__dirname,'./dist'),
filename:'bundle.js'
}
};
3.6 新建index.html
<html>
<head>
</head>
<body>
<script src="dist/bundle.js"></script>
</body>
</html>
4. 打包css
4.1 安装loader
Webpack只能处理javascript模块,如果要处理css、png,则需要使用loader转换。
*注意版本匹配
npm install style-loader@0.23.1 css-loader@1.0.1 --save-dev
webpack@3.6.0
“css-loader”: “^1.0.1”,
“style-loader”: “^0.23.1”,
版本不匹配会报错:
TypeError: this.getOptions is not a function
通过npm uninstall css‐loader 卸载原版本less-loader,然后通过
npm install css‐loader@1.0.1
命令安装 css‐loader,解决。
4.2 src下新建css1.css
body{
background:red;
}
4.3 webpack.config.js
var path=require("path");
module.exports={
entry:'./src/main.js',
output:{
path:path.resolve(__dirname,'./dist'),
filename:'bundle.js'
},
module:{
rules:[
{
test:/\.css$/,use:['style-loader','css-loader']
}
]
}
};
4.4 main.js
在main.js增加一行:
require('./css1.css');
4.5 打包
运行webpack