## webpack
1、安裝`webpack`。
~~~
npm install --save-dev webpack
~~~
`tip: --save-dev` 是你開發時候依賴的東西,`--save` 是你發布之后還依賴的東西。[點這里了解更多](https://segmentfault.com/q/1010000005163089)
2、根據[webpack文檔](https://doc.webpack-china.org/guides/getting-started)編寫最基礎的配置文件。
新建webpack開發配置文件 `touch webpack.dev.config.js`
` webpack.dev.config.js`
~~~
'use strict'
const path = require('path')
module.exports = {
/*入口*/
entry: path.join(__dirname, 'src/index.js'),
/*輸出到dist文件夾,輸出文件名字為bundle.js*/
output: {
path: path.join(__dirname, './dist'), /*輸出目錄*/
filename: 'bundle.js' /*輸出文件名*/
}
}
~~~
3、使用`webpack`編譯文件。
新建入口文件`index.js`
`mkdir src && touch ./src/index.js`
`src/index.js` 內容如下
`document.getElementById('app').innerHTML = 'Webpack works'`
在git bash 上執行 `webpack --config webpack.dev.config.js`
> webpack 需要全局安裝,npm install -g webpack 這里-g是全局安裝
運行命令之后可以看到目錄多了dist 文件夾 里面有 bundle.js,但是并不能看到效果,所以需要一個html模板入口文件
4、新建一個 `index.html`。
`touch ./dist/index.html`
`dist/index.html`寫入內容
~~~
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="./bundle.js"></script>
</body>
</html>
~~~
這個過程叫做編譯,通過`webpack --config webpack.dev.config.js`我們指定了webpack幫我們做了一些東西。
讓它找到了`webpack.dev.config.js`文件,把入口文件 index.js 經過處理之后,生成 bundle.js。就這么簡單。