Webpack學習筆記
阿新 • • 發佈:2020-11-29
nrm的安裝和使用
作用,切換npm映象包的映象地址
使用:1.執行 npm i nrm -g 全域性安裝npm 包
2.使用 nrm ls 檢視當前所有可用的映象源地址以及當前使用的映象地址
3.使用nrm use 切換不同的映象地址
webpack
什麼是webpack
前端構建工具
webpack 安裝
npm i webpack -g
基本的命令
npm init --yes 生成package.json 檔案
webpack ./src/main.js -o ./dist/ 打包成瀏覽器可以識別的語法
通過配置檔案設定
const path = require('path'); module.exports={ entry:path.join(__dirname,'./src/main.js'),//入口表示 檔案要打包的路徑 output:{ path:path.join(__dirname,'./dist'),//指定 打包好的檔案 輸出到哪個檔案中去 filename:'main.js' } }
webpack-dev-server
開發時監聽程式碼變化 自動打包js得外掛
webpack-dev-server 安裝
npm i webpack-dev-server -D
配置命令
package.json 配置
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server" //簡配版
}
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack-dev-server --open --port 3000 --contentBase src --hot" } //自動開啟瀏覽器 設定埠 內容入口 熱更新
webpack.config.js 配置
const path = require('path'); const webpack = require('webpack');//熱更新1 module.exports={ entry:path.join(__dirname,'./src/main.js'),//入口表示 檔案要打包的路徑 output:{ path:path.join(__dirname,'./dist'),//指定 打包好的檔案 輸出到哪個檔案中去 filename:'main.js' }, devServer:{ open:true, port:5000, contentBase:'src', hot:true //熱更新2 }, plugins:[ new webpack.HotModuleReplacementPlugin(),//熱更新3 ] }
html-webpack-plugin
開發時自動打包html的外掛
安裝
npm i html-webpack-plugin -D
webpack.config.js 配置
const htmlWebpackPlugin = require('html-webpack-plugin') //引用模組
plugins:[
new webpack.HotModuleReplacementPlugin(),//熱更新3
new htmlWebpackPlugin({
template:path.join(__dirname,'./src/index.html'),//指定得模板頁
filename:'index.html'
})//將html 放到記憶體中
]
樣式模組管理
處理css檔案,less檔案 (scss 同理)
安裝打包外掛 npm i style-loader css-loader -D
npm i less less-loader -D
webpack.config.js 配置module
module:{
rules:[{
test:/\.css$/,use:['style-loader','css-loader'] //loader 呼叫順序從右到左
},
{
test:/\.less$/,use:['style-loader','css-loader','less-loader']
}]
}
Babel
npm i babel-core babel-loader babel-plugin-transform-runtime -D
npm i bable-preset-env babel-preset-statge-0 -D
{test:/\.js$/,use:['babel-loader','exclude:/node_moudle']}
出現的問題
問題1 webpack webpack-cli webpack-dev-server 安裝了也無法正常使用
//由於版本之間的問題 會出現命令無法正常使用的情況
//可以使用的版本
"devDependencies": {
"webpack": "^5.1.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
}