當前位置:
首頁 > 知識 > webpack 實現的多入口項目腳手架

webpack 實現的多入口項目腳手架

簡介

基於 webpack2 實現的多入口項目腳手架,主要使用 extract-text-webpack-plugin 實現 js 、css 公共代碼提取,html-webpack-plugin 實現 html 多入口,less-loader 實現 less 編譯,postcss-loader 配置 autoprefixer 實現自動添加瀏覽器兼容前綴,html-withimg-loader 實現 html 內引入圖片版本號添加和模板功能,babel-loader 實現 ES6 轉碼功能, happypack 多線程加速構建速度。

目錄

├── dist # 構建後的目錄
├── config # 項目配置文件
│ ├── webpack.config.js # webpack 配置文件
│ └── postcss.config.js # postcss 配置文件
├── src # 程序源文件
│ └── js # 入口
│ ├ └── index.js # 匹配 view/index.html
│ ├ └── user
│ ├ ├ ├── index.js # 匹配 view/user/index.html
│ ├ ├ ├── list.js # 匹配 view/user/list.html
│ ├ └── lib # JS 庫等,不參與路由匹配
│ ├ ├── jquery.js
│ └── view
│ ├ └── index.html # 對應 js/index.js
│ ├ └── user
│ ├ ├── index.html # 對應 js/user/index.js
│ ├ ├── list.html # 對應 js/user/list.js
│ └── css # css 文件目錄
│ ├ └── base.css
│ ├ └── iconfont.css
│ └── font # iconfont 文件目錄
│ ├ └── iconfont.ttf
│ ├ └── iconfont.css
│ └── img # 圖片文件目錄
│ ├ └── pic1.jpg
│ ├ └── pic2.png
│ └── template # html 模板目錄
│ └── head.html
│ └── foot.html

配置多入口

根據 JS目錄獲取多入口數組

const ROOT = process.cwd; // 根目錄

let entryJs = getEntry("./src/js/**/*.js");

/**
* 根據目錄獲取入口
* @param {[type]} globPath [description]
* @return {[type]} [description]
*/
function getEntry (globPath) {
let entries = {};
Glob.sync(globPath).forEach(function (entry) {
let basename = path.basename(entry, path.extname(entry)),
pathname = path.dirname(entry);
// js/lib/*.js 不作為入口
if (!entry.match(//js/lib//)) {
entries[pathname.split("/").splice(3).join("/") + "/" + basename] = pathname + "/" + basename;
}
});
return entries;
}

// webpack 配置
const config = {
entry: entryJs,
output: {
filename: "js/[name].js?[chunkhash:8]",
chunkFilename: "js/[name].js?[chunkhash:8]",
path: path.resolve(ROOT, "dist"),
publicPath: "/"
},
}

module

使用 babel 實現 ES2015 轉 ES5,less 轉 css 並使用 postcss 實現 autoprefixer 自動添加瀏覽器兼容,url-loader 實現 css 引用圖片、字體添加版本號,html-withimg-loader 實現 html 引用圖片添加版本號並實現模板功能。

module: {
rules: [
{
test: /.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader?id=js",
options: {
presets: ["env"]
}
}
},
{
test: /.(less|css)$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader?id=styles",
use: [{
loader: "css-loader?id=styles",
options: {
minimize: !IsDev
}
},
{
loader: "less-loader?id=styles"
},
{
loader: "postcss-loader?id=styles",
options: {
config: {
path: PostcssConfigPath
}
}
}
]
})
},
{
test: /.(png|jpg|gif)$/,
use: [
{
loader: "url-loader",
options: {
limit: 100,
publicPath: "",
name: "/img/[name].[ext]?[hash:8]"
}
}
]
},
{
test: /.(eot|svg|ttf|woff)$/,
use: [
{
loader: "url-loader",
options: {
limit: 100,
publicPath: "",
name: "/font/[name].[ext]?[hash:8]"
}
}
]
},
// @see https://github.com/wzsxyz/html-withimg-loader
{
test: /.(htm|html)$/i,
loader: "html-withimg-loader?min=false"
}
]
},

// postcss.config.js
module.exports = {
plugins: [
require("autoprefixer")({
browsers: ["> 1%", "last 5 versions", "not ie <= 9"], }) ] }

View 視圖

根據目錄對應關係,獲取 js 對應的 html 入口

let entryHtml = getEntryHtml("./src/view/**/*.html"),
configPlugins;

entryHtml.forEach(function (v) {
configPlugins.push(new HtmlWebpackPlugin(v));
});

// webpack 配置
resolve: {
alias: {
views: path.resolve(ROOT, "./src/view")
}
},

/**
* 根據目錄獲取 Html 入口
* @param {[type]} globPath [description]
* @return {[type]} [description]
*/
function getEntryHtml (globPath) {
let entries = ;
Glob.sync(globPath).forEach(function (entry) {
let basename = path.basename(entry, path.extname(entry)),
pathname = path.dirname(entry),
// @see https://github.com/kangax/html-minifier#options-quick-reference
minifyConfig = IsDev ? "" : {
removeComments: true,
collapseWhitespace: true,
minifyCSS: true,
minifyJS: true
};

entries.push({
filename: entry.split("/").splice(2).join("/"),
template: entry,
chunks: ["common", pathname.split("/").splice(3).join("/") + "/" + basename],
minify: minifyConfig
});

});
return entries;
}

plugins

使用 happypack 多線程加快構建速度,CommonsChunkPlugin 實現提取公用 js 為單獨文件,extract-text-webpack-plugin 實現提取公用 css 為單獨文件,

let configPlugins = [
new HappyPack({
id: "js",
// @see https://github.com/amireh/happypack
threadPool: HappyThreadPool,
loaders: ["babel-loader"]
}),
new HappyPack({
id: "styles",
threadPool: HappyThreadPool,
loaders: ["style-loader", "css-loader", "less-loader", "postcss-loader"]
}),
new webpack.optimize.CommonsChunkPlugin({
name: "common"
}),
// @see https://github.com/webpack/webpack/tree/master/examples/multiple-entry-points-commons-chunk-css-bundle
new ExtractTextPlugin({
filename: "css/[name].css?[contenthash:8]",
allChunks: true
})
];

entryHtml.forEach(function (v) {
configPlugins.push(new HtmlWebpackPlugin(v));
});

// webpack 配置
plugins: configPlugins,

開發

webpack-dev-server 實現開發環境自動刷新等功能

// webpack 配置
devServer: {
contentBase: [
path.join(ROOT, "src/")
],
hot: false,
host: "0.0.0.0",
port: 8080
}

開發

npm start

構建

cross-env 實現區分開發和生產環境構建


命令 說明
npm run dev 開發環境構建,不壓縮代碼
npm run build 生產環境構建,壓縮代碼

倉庫

歡迎 star

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 科技優家 的精彩文章:

Java NIO原理分析
PHP設計模式:簡單工廠
巧設publicPath,優雅適配生產環境要求
Linux網路編程客戶伺服器設計範式

TAG:科技優家 |

您可能感興趣

Python web開發:Flask的項目配置
3個簡單上手的arduino項目
投資專家Kari Mork加入Market.space成為項目顧問
瑞波幣創始人jed mccaleb的另一個項目
快速開啟你的第一個項目:TensorFlow項目架構模板
繼Aquila之後,Facebook宣布砍掉另一個空中聯網無人機項目Tether
推薦Android幾個比較實用的Github開源項目
pallet one:下一個百倍跨鏈項目
flask 項目中使用 bootstrapFileInput
springboot項目初始化
blogfoster-scripts:一款簡化 Node.js 項目初始化的工具
Decred 的未來:項目負責人 Jake Yocom-Piatt 獨家專訪
如何成為 Apache 項目的 committer
項目簡說之block collider
Viptela+Cisco首個項目落地聯想
OpenWatch項目:給你的智能手錶更多ROM選擇
用 jest 單元測試改善老舊的 Backbone.js 項目
OpenStack自己的容器管理項目Zun的實踐
Github 項目推薦 用PyTorch 實現 OpenNMT
GitHub項目 | PyTorch 中文手冊