webpack4入門和使用
webpack介紹
這是webpak的上的基本的介紹:本質上,webpack 是一個現代 JavaScript 應用程序的靜態模塊打包器(static module bundler)。在 webpack 處理應用程序時,它會在內部創建一個依賴圖(dependency graph),用於映射到項目需要的每個模塊,然後將所有這些依賴生成到一個或多個bundle。
webpack的文檔 https://webpack.docschina.org...
新接手的項目,從輪子開始就自己搭建。網上也找了很久的,也沒找到很合適的輪子,那就自己建一個吧。wewebpack4 也更新了很多東西。
新建項目
mkdir webpack-init
cd webpack-init
npm init
之後就跟着提示把package.json中的信息補充完整就可以了.
新建JS文件
目錄
.
├── ./package.json
├── ./src
│ └── ./src/index.js
├── ./webpack.config.js
├── ./yarn-error.log
└── ./yarn.lock
其中webpack.config.js 如下
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin'); //通過 npm 安裝
module.exports = {
entry: './src/index.js', //入口文件,src下的index.js
output: {
path: path.join(__dirname, 'dist'), // 出口目錄,dist文件
filename: '[name].[hash].js' //這裏name就是打包出來的文件名,因爲是單入口,就是main,多入口下回分解
},
module: {},
plugin: [],
devServer: {
contentBase: path.join(__dirname, 'dist'), //靜態文件根目錄
port: 8080, // 端口
host: 'localhost',
overlay: true,
compress: true // 服務器返回瀏覽器的時候是否啓動gzip壓縮
}
};
添加插件
js文件加載
yarn add ]babel-core babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-0 -D
新建.babelrc 文件
{
"presets": [
"es2015",
"react",
"stage-0"
],
"plugins": []
//babel-core 調用Babel的API進行轉碼
//babel-loader
//babel-preset-es2015 用於解析 ES6
//babel-preset-react 用於解析 JSX
//babel-preset-stage-0 用於解析 ES7 提案
}
/*src文件夾下面的以.js結尾的文件,要使用babel解析*/
/*cacheDirectory是用來緩存編譯結果,下次編譯加速*/
module: {
rules: [{
test: /\.js$/,
use: ['babel-loader?cacheDirectory=true'],
include: path.join(__dirname, 'src')
}]
}
css文件加載
yarn add style-loader -D
yarn add css-loader -D
添加配置:
rules: {
test: /\.css$/,
use: ['style-laoder', 'css-loader'],
include: path.join(__dirname, 'src'), //限制範圍,提高打包速度
exclude: /node_modules/
}
html模板生成
//通過 npm 安裝 webpack.config.js頭部添加
const HtmlWebpackPlugin = require('html-webpack-plugin');
//插件添加
plugin: [
// 通過new一下這個類來使用插件
new HtmlWebpackPlugin({
// 用哪個html作爲模板
// 在src目錄下創建一個index.html頁面當做模板來用
template: './src/index.html',
hash: true // 會在打包好的bundle.js後面加上hash串
})
]
複製靜態資源
yarn add copy-webpack-plugin -D
添加插件配置
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, 'public/static'),
to: path.resolve(__dirname, 'dist/static'),
ignore: ['.*']
}
])
文章未完成,待完善