Webpack是一款用户打包前端模块的工具。主要是用来打包
在浏览器端使用的javascript的。同时也能转换、捆绑、打包其他的静态资源,包括css、image、font file、template
等,并且支持AMD/CMD
优势如下:
$ npm init -y
$ npm install -g webpack
$ npm install webpack --save-dev
$ webpack 入口文件 出口文件
$ npm install style-loader css-loader less-loader sass-loader --save-dev
require('style!css!less!./style.less');
require('style!css!less!./style.scss');
$ mkdir src build
$ cd src && touch component.js
$ cd src && touch index.js
$ cd build && touch index.html
<script src="bundle.js"></script>
$ touch webpack.config.js
var path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'src/index.js'),//打包的入口文件 String|Object
output: { //配置打包结果 Object
path: path.resolve(__dirname, 'build'),//定义输出文件路径
filename: 'bundle.js' //指定打包文件名称
}
};
"scripts": {
+ "build": "webpack"
}
$ npm run build 相当于执行webpack
module: {
loaders: [
{
test: /\.less/,
loader:'style!css!less'
}
],
},
$ npm install file-loader url-loader --save-dev
module: {
loaders: [
{
test: /\.less/,
loader:'style!css!less'
},
+ {
+ test: /\.(woff|woff2|ttf|svg|eot)(\?v=\d+\.\d+\.\d+)?$/,
+ loader: "url?limit=10000"
+ },
+ {
+ test: /\.(jpg|png)$/,
+ loader: "url?limit=8192&name=[name].[ext]"
+ }
],
},
entry: {
entry1: './src/component.js',
entry2: './src/index.js',
},
output:{
path:'./build/',
+ filename:'[name].js'
},
指定extension之后可以不用在require或是import的时候加文件扩展名,会依次尝试添加扩展名进行匹配
resolve: {
extensions: ["", ".js", ".jsx", ".css", ".json"],
}
+ var jqueryPath = path.join(__dirname, "./node_modules/jquery/dist/jquery.js");
resolve: {
extensions: ["", ".js", ".jsx", ".css", ".json"],
+ alias: {
+ 'jquery': jqueryPath
+ }
}
module: {
loaders: [
{
test: /\.less/,
loader:'style!css!less'
},
+ {
+ test: /\.(woff|woff2|ttf|svg|eot)(\?v=\d+\.\d+\.\d+)?$/,
+ loader: "url?limit=10000"
+ },
+ {
+ test: /\.(jpg|png)$/,
+ loader: "url?limit=8192&name=[name].[ext]"
+ }
],
+ noParse: [jqueryPath]
},
引用jquery
var $ = require('jqeury');
$('#app').html('hello zfpx');
webpack-dev-server是一个Web服务器,可以预览。
项目在内存中打包,不是io读写
$ npm install webpack-dev-server -g
$ npm install webpack-dev-server --save-dev
devServer: {
publicPath: "/static/",//设置在html页面中访问产出文件的路径前缀
stats: { colors: true }, //显示颜色
port: 8080,//端口
contentBase: 'build',//指定静态文件的根目录
}
<script src="/static/bundle.js"></script>
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack"
},
$ npm run dev