項(xiàng)目的依賴
開(kāi)發(fā)依賴(devDependencies): webpack, webpack-cli
項(xiàng)目的默認(rèn)結(jié)構(gòu):
- 入口:/src/index.js
- 出口:/dist/main.js
webpack.config.js的默認(rèn)配置:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
生成調(diào)試使用的source map
devtool: 'source-map'
加入loader的配置
module: {
rules: [
{test: /\.css$/, use: ['style-loader', 'css-loader']},
{test: /\.png$/, use: ['file-loader']}
]
}
更具體化的loader配置
rules: [
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true
}
}
]
}
]
內(nèi)聯(lián) 方式的loader
import Styles from 'style-loader!css-loader?modules!./styles.css';
全局方式的引入(以JQuery為例)
- 引正常的模塊引入的方式:
import $ from 'jquery'
這種方式是以局部變量的方式驼抹,引入,如:BootStrap)括勺。
- 采用expose-loader進(jìn)行引入
該模塊的作用是用來(lái)將模塊以全局變量的方式引入
cnpm i -D expose-loader
此時(shí)引入的代碼:
import 'expose-loader?$!jquery
如果引入lodash可以采用
import 'expose-loader?_!lodash
url-loader和file-loader
- 它們的基本作用都是可以圖片,字體卷胯,矢量引入摊趾。
- 但url-loader更加智能的,可以設(shè)定一個(gè)閥值藤肢,來(lái)確定使用base64編譯還是原生值來(lái)進(jìn)行加載,配置如下:
{
test: /\.(png|svg|jpg|jpeg|gif)$/,
loader: 'url-loader',
options: {
limit: 12000
}
}
構(gòu)建前清理dist文件夾
const CleanWebpackPlugin = require('clean-webpack-plugin');
...
plugins: [
new CleanWebpackPlugin()
]
自動(dòng)生成html
const HtmlWebpackPlugin = require('html-webpack-plugin');
...
plugins: [
new HtmlWebpackPlugin({
filename:'index.html',
template: 'index.html',
inject:'body'
})
],
- 其中的三個(gè)參數(shù)都可能省略糯景。
- filename: 表示dist/index.html
- template: 表示項(xiàng)目根下的index.html
- inject: 表示script腳注入的位置嘁圈,可選為body和head
控制輸出文件的數(shù)量
entry: {
app: "./src/index.js",
math: "./src/math.js"
},
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, 'dist')
},
此時(shí)省骂,在dist中生成的文件列表如下:
dist/app.bundle.js
dist/math.bundle.js
添加文件監(jiān)視功能
- 在package.json中:
"scripts": {
"watch": "webpack --watch",
...
- 運(yùn)行:
npm run watch
增加調(diào)試的web server(自帶文件監(jiān)視功能)
- 安裝
cnpm install --save-dev webpack-dev-server
- 在webpack.config.js
devServer: {
contentBase: './dist',
host: 'localhost',
port: 8080,
hot:true
},
- 以上幾項(xiàng)都是默認(rèn)項(xiàng)(可以零配置)
- hot 表示熱更新,即自動(dòng)刷新網(wǎng)頁(yè)
- 在package.json中
"scripts": {
"start": "webpack-dev-server --open",
- npm start