以前習慣用gulp+less來開發項目,由於公司項目用的vue開發的,所以學下webpack這個打包工具。以下是我學習時的筆記,希望給在webpack配置過程中遇到麻煩的朋友一絲幫助。
目前只配置了sass,css,js,html,es6,圖片編譯,字體引入,熱加載這幾項,簡單項目已經夠用。
如果深入webpack可以配置很多,原諒我也只是初次配置
1.首先建一個自己的項目文件夾,npm init -y快速生成一個配置文件
2. npm i webpack -D 本地安裝webpack
3. npm i webpack-dev-server -g 全局安裝webpack-dev-server
4. npm i webpack-dev-server -D 添加到package.json文件里
5.以下是我的package.json,里面的包都是常用的
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server",
"build": "webpack"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.0.0",
"babel-loader": "^6.0.0",
"babel-preset-latest": "^6.0.0",
"cross-env": "^3.0.0",
"css-loader": "^0.28.0",
"file-loader": "^0.9.0",
"extract-text-webpack-plugin": "^2.1.0",
"html-webpack-plugin": "^2.28.0",
"node-sass": "^4.5.2",
"sass-loader": "^6.0.3",
"style-loader": "^0.16.1",
"webpack": "^2.2.0",
"webpack-dev-server": "^2.4.2"
}
}
根目錄下的webpack.config.json
// html壓縮
var HtmlWebpackPlugin = require('html-webpack-plugin');
// js css分離
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path')
var webpack = require('webpack')
module.exports = {
// 配置入口文件
entry: {
build: './src/main.js'
},
// 配置輸出路徑
output: {
path: path.resolve(__dirname, './dist'),
// publicPath: '/dist/',//指定資源引用目錄
filename: '[name].js'
},
// loader模塊配置
module: {
loaders: [
// js 文件
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
// css 文件
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
//解析.scss文件
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ["css-loader", "sass-loader"]
})
},
// 字體
{
test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
loader: 'file-loader'
},
// 圖片
{
test: /\.(png|jpe?g|gif|svg)(\?\S*)?$/,
loader: 'file-loader',
query: {
name: '[name].[ext]?[hash]'
}
}
]
},
// 插件配置
plugins: [
new HtmlWebpackPlugin({
template: './index.html' // 模版文件
}),
new ExtractTextPlugin({
filename: 'style.css'
/*filename: (getPath) => {
return getPath('dist/[name].css').replace('dist','css')
}*/
})
],
// webpack-dev-server 熱加載
devServer: {
historyApiFallback: true,
noInfo: true
},
devtool: '#eval-source-map'
}
.babelrc文件
{
"presets": [
["latest", {
"es2015": { "modules": false }
}]
]
}
index.html移入編譯后的文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" type="text/css" href="dist/styls.css"> <script src="dist/build.js"></script> </head> <body> <h1>hello</h1> <h2>hello</h2> <p>hello <span>hello world</span></p> </body> </html>
我的項目目錄
main.js里面移入所有需要打包的文件
import {hello,hello1} from './script/hello1'; import {demo} from './script/hello'; import './style/hello.css'; import './style/hello.scss';
命令行npm start 啟動項目 npm run build 編譯項目
我托管到了github,有興趣的同學可以參考下:https://github.com/wmui/webpack-demo