webpack
webpack簡介
webpack 示例
源代碼來源:how2java—webpack
簡單打包
指令行方式
安裝webpack,使用全局安裝模式。
cnpm install -g [email protected]
一個簡單的a.js:
運作打包指令:
webpack a.js bundle.js
一個index.html檔案:
<html>
<head>
<script src="bundle.js"></script>
</head>
</html>
測試後:可以看到成功打包了。
這裡直接使用打開檔案的方式。
配置檔案 方式
webpack.config.js:
module.exports = {
entry: './a.js',
output: {
filename: 'bundle.js'
}
};
這裡直接使用打開檔案的方式。
配置伺服器
使用 WEBPACK-DEV-SERVER
安裝:
全局安裝
cnpm install -g [email protected]
運作:
使用
webpack-dev-server --open
:
運作相應的浏覽器,并打開預設的
index.html
頁面
顯示:
顯示如下位址的通路:
http://localhost:8080/webpack-dev-server/
端口:
module.exports = {
entry: './a.js',
output: {
filename: 'bundle.js'
},
devServer: {
port:8088
}
}
熱更新:
var webpack = require('webpack')
module.exports = {
entry: './a.js',
output: {
filename: 'bundle.js'
},
plugins:[
new webpack.HotModuleReplacementPlugin()
],
devServer: {
port:8088,
inline:true,
hot:true
}
}
npm 啟動方式
運作
npm init -y
:配置得到初始的json檔案。
{
"name": "webpack-demo",
"version": "1.0.0",
"main": "a.js",
"scripts": {
"dev": "webpack-dev-server --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"webpack": "^1.13.2"
},
"devDependencies": {},
"description": ""
}
運作:
npm run devnpm run dev
。
dev
訓示腳本的内容。
使用
http://localhost:8088/
測試。
多個入口檔案
配置一個如下的json檔案:
module.exports = {
entry: {
bundle1: './a.js',
bundle2: './b.js'
},
output: {
filename: '[name].js'
},
devServer: {
port:8088
}
}
bundle1 對應a.js 而bundle2 對應 b.js。
相容es6
有的時候浏覽器,推出一些新的特性卻沒有傳播。
babel 安裝
一個es6寫法檔案 a.js
const name = 'ES6'
document.write(`hello ${name}`)
package.config.js配置:
test: /\.js$/,
:表示僅僅轉換js‘檔案。
loader: 'babel',
:使用babel loader進行 es6 轉換。
query:{ presets: ['latest'] }
: latest 表示用最新的文法規則進行
loaders: [
{
test: /\.js$/,
loader: 'babel',
query:{
presets: ['latest']
}
}
然後發現修改完畢的js語句應該是符合es5标準的了。
css子產品引入
在webpack的概念之中,所有的檔案都是子產品。
通過如下指令安裝css-loader和style-loader:
npm install [email protected] [email protected] --save-dev
準備css檔案:
body {
background-color: blue;
}
在配置檔案中增加.css的配置:
module.exports = {
entry: './a.js',
output: {
filename: 'bundle.js'
},
devServer: {
port:8088
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query:{
presets: ['latest']
}
},
{
test:/\.css/,
loader:'style-loader!css-loader'
}
]
}
}
修改a.js:
require("./style.css")
const name = 'ES6'
document.write(`hello ${name}`)
參考
源代碼來源:how2java—webpack