webpack配置文件
之前是依賴全局環境下的打包過程,下面將 webpack 安裝到項目的依賴中,這樣就可以使用項目本地版本的 webpack
- 首先創建package.json文件:
npm init
自動生成後如下:
{
"name": "webpack-package.json",
"version": "1.0.0",
"description": "",
"main": "bundle.js",
"dependencies": {},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"webpack"
],
"author": "yangll",
"license": "ISC"
}
- 安裝項目環境
npm install webpack --save-dev //安裝
npm uninstall webpack --save-dev //卸載
- 設置Webpack 的配置文件webpack.config.js
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: path.resolve(__dirname, './entry.js'),
output: {
path: path.resolve(__dirname, './'),
filename: 'bundle.js',
},
};
- 命令後執行webpack完成打包
webpack
打包日誌如下
Hash: 71820986fc674176394e
Version: webpack 1.13.1
Time: 82ms
Asset Size Chunks Chunk Names
bundle.js 1.42 kB 0 [emitted] main
[0] ./entry.js 27 bytes {0} [built]
設置 package.json scripts
把下面的內容添加到 package.json
"scripts": {
"build": "webpack"
}
然後輸入 npm run build 就可以編譯了
啓動webpack內置服務器環境
使用 webpack-dev-server 開發服務是一個更好的選擇。它將在 localhost:8080 啓動一個 express 靜態資源 web 服務器,並且會以監聽模式自動運行 webpack,在瀏覽器打開 http://localhost:8080/ 或 http://localhost:8080/webpack-dev-server/ 可以瀏覽項目中的頁面和編譯後的資源輸出,並且通過一個 socket.io 服務實時監聽它們的變化並自動刷新頁面。
安裝
$ npm install webpack-dev-server --save-dev
啓動
webpack-dev-server
日誌
http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from D:\project
Hash: 71820986fc674176394e
Version: webpack 1.13.1
Time: 141ms
Asset Size Chunks Chunk Names
bundle.js 1.42 kB 0 [emitted] main
chunk {0} bundle.js (main) 27 bytes [rendered]
[0] ./entry.js 27 bytes {0} [built]
webpack: bundle is now VALID.
然後訪問http://localhost:8080就能看到頁面打印It works.這樣一個簡單的本地服務器環境就配置完成了。