安装
npm install --save-dev webpacknpm install --save-dev webpack-cli //4.x以上版本,用于cli命令
npm install -g webpacknpm install -g webpack-cli
初始化项目
npm init -y //自动生成一个package.json文件npm install webpack webpack-cli --save-dev
//package.json { "name": "webpack-demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "webpack": "^4.0.1", "webpack-cli": "^2.0.9", "lodash": "^4.17.5" } }//webpack.config.jsconst path = require('path'); module.exports = { entry: './src/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') } }; //index.html<!doctype html><html> <head> <title>demo</title> </head> <body> <script src="./src/index.js"></script> </body></html>//index.jsfunction component() { var element = document.createElement('div'); var node = document.createTextNode("hello,webpack!"); element.appendChild(node); return element;}document.body.appendChild(component());
下载安装包
//production模式npm install --save [+安装包名称]//development模式npm install --save-dev
运行项目
npx webpack
//package.json { "name": "webpack-demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1",+ "build": "webpack" //新增 }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "webpack": "^4.0.1", "webpack-cli": "^2.0.9", "lodash": "^4.17.5" } }
loader
// webpack.config.js module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ] }
module: { rules: [ { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] } ] }
module: { rules: [ { test: /\.(woff|woff2|eot|ttf|otf)$/, use: [ 'file-loader' ] } ] }
module: { rules: [ { test: /\.(csv|tsv)$/, use: [ 'csv-loader' ] }, { test: /\.xml$/, use: [ 'xml-loader' ] } ] }
插件的使用
npm install --save-dev html-webpack-plugin
const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', + plugins: [+ new HtmlWebpackPlugin({+ title: 'Output Management'+ })+ ], output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') } };
source map
// webpack.config.js const path = require('path'); module.exports = { entry: './src/index.js',+ devtool: 'source-map', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') } };
开发工具
安装
npm install --save-dev webpack-dev-server
使用
//webpack.config.js const path = require('path'); module.exports = { entry: './src/index.js',+ devServer: {+ contentBase: './dist'+ }, output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') } };