loaders
例 加载CSS文件
yarn add css-loader style-loader -D
配置文件
const config = {entry: './src/index.js',output: {filename: 'bundle.js',path: path.join(__dirname, './dist')},module: {rules: [{test: /\.css$/,use: ['style-loader', 'css-loader']//处理顺序是从后往前,先使用css-loader处理,然后使用style-loader处理}]}}module.exports = config;
入口文件
require('./index.css');console.log('hello webpack');
如果想让webpack还能处理scss
yarn add sass-loader sass -D#这里知道要安装sass是运行webpack报错后,看错误信息知道还需要安装sass
配置文件
const path = require('path');const config = {entry: './src/index.js',output: {filename: 'bundle.js',path: path.join(__dirname, './dist')},module: {rules: [{test: /\.(scss|sass)$/,use: ['style-loader', 'css-loader', 'sass-loader']}]}}module.exports = config
入口文件
require('./index.scss');console.log('hello webpack');
plugins
例如 html-webpack-plugin 的使用
yarn add html-webpack-plugin -D
配置文件
const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');const config = {entry: './src/index.js',output: {filename: 'bundle.js',path: path.join(__dirname, './dist')},module: {rules: [{test: /\.(scss|sass)$/,use: ['style-loader', 'css-loader', 'sass-loader']}]},plugins: [new HtmlWebpackPlugin({filename: 'index.html', //这是生成的html文件的名字template: './index.html' //这是引用的html文件的模板})]}module.exports = config/*这样,生成的dist目录中除了bundle.js还会有一个已经引用了bundle.js文件的html,这个html来源于模板index.html*/
现在我们每次修改完都需要运行webpack才能生成新的打包文件,如果能监听变化自动打包就好了
package.json添加新的npm脚本
//...其他代码"script": {"build": "webpack","watch": "webpack --watch"}//...其他代码
这样,每次修改文件都会自动打包生成目标文件,如果修改js能在浏览器里面自动刷新就好了
HMR
yarn add webpack-dev-server
package.json
//...其他代码"script": {"build": "webpack","watch": "webpack --watch","hot": "webpack-dev-server"}//...其他代码
webpack.config.js
const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');+const webpack = require('webpack');const config = {entry: './src/index.js',output: {filename: 'bundle.js',path: path.join(__dirname, './dist')},module: {rules: [{test: /\.(scss|sass)$/,use: ['style-loader', 'css-loader', 'sass-loader']}]},+devServer: {+contentBase: './dist',+hot: true+},plugins: [new HtmlWebpackPlugin({filename: 'index.html',template: './index.html'}),+new webpack.HotModuleReplacementPlugin()]}module.exports = config
