中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

webpack配置的最佳實踐分享

發布時間:2020-10-08 14:35:46 來源:腳本之家 閱讀:226 作者:Hi-FE 欄目:web開發

本文主要介紹了關于webpack配置的最佳實踐,本文分享的實踐具有以下的優勢:

  • 使用happypack提升打包速度。
  • 使用MD5 hash可以生成文件版本,進行版本控制
  • 在非單頁面的系統中支持多個入口的配置
  • 模板中可以利用htmlplugin輸出一些配置性的信息
  • 支持devserver,支持本地json數據的mock

一、webpack最佳實踐中的需求

     1.熱加載

     2.語法校驗

     3.js打包

     4.模板打包

二、解決方案

1.webpack.config.json

var path = require('path');
var fs = require('fs');
var exec = require('child_process').exec;
var HappyPack = require('happypack');
var merge = require('webpack-merge');
var webpack = require('webpack');
var WebpackMd5Hash = require('webpack-md5-hash');
var HtmlwebpackPlugin = require('html-webpack-plugin');
var ROOT_PATH = path.resolve(__dirname);
var APP_PATH = path.resolve(ROOT_PATH, 'app');
var BUILD_PATH = path.resolve(ROOT_PATH, __dirname+'/devserver/public');
//取出頁面文件映射
function getHtmlPluginArr() {
 var data = JSON.parse(fs.readFileSync('entryconf.json', 'utf-8'));
 var pageList = data.pageList;
 var resultObj = {
 "pluginArr": [],
 "entryObj": {}
 };
 for (var index = 0; index < pageList.length; index++) {
 var element = pageList[index];
 var entry = element.entry;
 //通過對app.json中src的路徑截取獲得分發路徑
 var filename = (function () {
 var filenameStr = entry.split("./app/page/")[1];
 return filenameStr.substr(0, filenameStr.lastIndexOf("."));
 })();
 var title = element.title;
 var extra = element.extra;
 resultObj.entryObj[filename] = entry;
 //利用路徑一部分來進行HtmlwebpackPlugin的chunks
 resultObj.pluginArr.push(
 new HtmlwebpackPlugin({
  chunks: [filename], //當前頁面js
  title: title,
  extra: extra,//包含頁面額外的配置信息
  template: "app/" + "template.ejs",
  filename: 'views/'+filename + '.ejs',
  chunksSortMode: "dependency"http://按chunks的順序對js進行引入
 })
 );
 //HappyPack, loader多進程去處理文件
 resultObj.pluginArr.push(
 new HappyPack({ id: 'html' }),
 new HappyPack({ id: 'css' }),
 new HappyPack({ id: 'js' }),
 new HappyPack({ id: 'tpl' })
 );
 }
 return resultObj;
}
var appJsonObj = getHtmlPluginArr();
/**通用配置 */
var commonConfig = {
 entry: appJsonObj.entryObj,
 module: {
 loaders: [
 { test: /\.html$/, loader: "html?minimize=false", happy: {id: "html"} },
 { test: /\.json$/, loader: "json" },
 { test: /\.scss|\.css$/, loaders: ["style", "css", "sass"], happy: {id: "css"} },
 { test: /\.(?:jpg|gif|png)$/, loader: 'url?limit=10240&name=images/[name]-[hash:10].[ext]' },
 { test: /\.handlebars/, loader: "handlebars", query: { helperDirs: [APP_PATH + "/helper"] }, happy: {id: "tpl"} },
 { test: /\.js$|\.jsx$/, exclude: /(node_modules|bower_components)/, loader: 'babel', query: { presets: ['es2015'] }, happy: {id: "js"} },
 ]
 },
 output: {
 path: BUILD_PATH,
 filename: "js/[name].js"
 },
 externals: {
 "jquery": "jQuery"
 },
 //配置短路徑引用
 resolve: {
 extensions: ['', '.js', '.json', '.scss','.vue'],
 alias: {
 vue : 'vue/dist/vue.js'
 }
 },
 plugins: appJsonObj.pluginArr,
 cache: true
}
module.exports = merge(commonConfig, {
 output: {
 publicPath: '/',
 path: BUILD_PATH,
 filename: "js/[name]-[chunkhash:10].js"
 },
 plugins: [
 new webpack.optimize.UglifyJsPlugin({ minimize: true }),
 new WebpackMd5Hash()
 ]
});

2.模板文件的配置:

<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
 <title>
 <%= htmlWebpackPlugin.options.title || '上單'%>
 </title>
</head>
<body>
 <div id="main-container"></div>
 <% if (htmlWebpackPlugin.options.extra&&htmlWebpackPlugin.options.extra.js) {%>
 <% for(var i = 0;i < htmlWebpackPlugin.options.extra.js.length;i++){ %>
 <script src="<%= htmlWebpackPlugin.options.extra.js[i] %>"></script>
 <% } %>
 <% } %>
</body>
<script src="http://cdn.bootcss.com/jquery/2.2.3/jquery.min.js"></script>
</html>

3.webpack.dev.config.json配置

var path = require('path');
var fs = require('fs');
var merge = require('webpack-merge');
var webpack = require('webpack');
var HtmlwebpackPlugin = require('html-webpack-plugin');
var OpenBrowserPlugin = require('open-browser-webpack-plugin');
var ROOT_PATH = path.resolve(__dirname);
var APP_PATH = path.resolve(ROOT_PATH, 'app');
var BUILD_PATH = path.resolve(ROOT_PATH, 'build');
var MODULE_PATH = path.resolve(ROOT_PATH, 'node_modules');
//取出頁面文件映射
function getHtmlPluginArr() {
 var data = JSON.parse(fs.readFileSync('app/entries.json', 'utf-8'));
 var pageList = data.pageList;
 var resultObj = {
 "pluginArr": [],
 "entryObj": {}
 };
 for (var index = 0; index < pageList.length; index++) {
 var element = pageList[index];
 var src = element.entry;
 //通過對app.json中src的路徑截取獲得分發路徑
 var dist = (function() {
 var s1 = src.split("./app/entries/")[1];
 var s2 = s1.substr(0, s1.lastIndexOf("/"));
 return s2;
 })();
 var title = element.title;
 var extra = element.extra;
 resultObj.entryObj[dist] = src;
 //利用路徑一部分來進行HtmlwebpackPlugin的chunks
 resultObj.pluginArr.push(
 new HtmlwebpackPlugin({
 chunks: [dist], //當前頁面js
 title: title,
 extra: extra,//包含頁面額外的配置信息
 template: "app/" + "template.ejs",
 filename: dist + '.html',
 chunksSortMode: "dependency" //按chunks的順序對js進行引入
 })
 );
 }
 return resultObj;
}
var appJsonObj = getHtmlPluginArr();
/**通用配置 */
var commonConfig = {
 entry: appJsonObj.entryObj,
 module: {
 loaders: [
 { test: /\.html$/, loader: "html?minimize=false" },
 { test: /\.json$/, loader: "json" },
 { test: /\.scss|\.css$/, loaders: ["style", "css", "sass"] },
 { test: /\.(?:jpg|gif|png)$/, loader: 'url?limit=10240&name=../images/[name]-[hash:10].[ext]' },
 { test: /\.handlebars/, loader: "handlebars" },
 { test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: 'babel', query: { presets: ['es2015','stage-3','react'] } },
 { test: /\.jsx$/, exclude: /(node_modules|bower_components)/, loader: 'babel', query: { presets: ['react','stage-3','es2015']} }
 ]
 },
 output: {
 path: BUILD_PATH,
 filename: "js/[name].js"
 },
 externals: {
 "jquery": "jQuery"
 },
 //配置短路徑引用
 resolve: {
 alias: {
 module: path.resolve(APP_PATH, 'module'),
 service: path.resolve(APP_PATH, "services"),
 component: path.resolve(APP_PATH, "components"),
 entries: path.resolve(APP_PATH, "entries"),
 routes: path.resolve(APP_PATH, "routes"),
 node_modules: path.resolve(ROOT_PATH, 'node_modules')
 },
 extensions: ['', '.js', '.jsx']
 },
 plugins: appJsonObj.pluginArr,
 devtool: "cheap-source-map",
 cache: true
}
//webpack-dev-server 提供的是內存級別的server,不會生成build的文件夾
//訪問路徑直接參照build下的路徑 如http://127.0.0.1:8080/shop/updateShop.html
module.exports = merge(commonConfig, {
 devServer: {
 hot: true,
 inline: true,
 progress: true,
 host: process.env.HOST,
 port: "8808",
 proxy: {
 '/api/getLeftBar': {
 target: 'http://127.0.0.1:8808/mock',//dev
 secure: false
 },
 '/api/getIndexData': {
 target: 'http://127.0.0.1:8808/mock',//dev
 secure: false
 },
 '/api/getblogs': {
 target: 'http://127.0.0.1:8808/mock',//dev
 secure: false
 },
 '/panda/*': {
 target: 'http://10.4.233.139:8411/',//dev
 secure: false
 },
 //轉發至本地mock
 '/page3/*': {
 target: 'http://127.0.0.1:8808',
 secure: false
 }
 }
 },
 plugins: [
 new webpack.HotModuleReplacementPlugin(),
 new OpenBrowserPlugin({
 url: 'http://127.0.0.1:8808/test.html'
 })
 ]
});

總結

以上就是關于webpack最佳配置的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

庆城县| 获嘉县| 南充市| 定西市| 红河县| 渑池县| 都安| 婺源县| 温宿县| 恩施市| 孟村| 蒙城县| 焦作市| 潮州市| 沧源| 河西区| 邹平县| 如东县| 嘉兴市| 高要市| 固镇县| 建瓯市| 呼玛县| 佛教| 莎车县| 扶风县| 琼海市| 英山县| 二连浩特市| 策勒县| 益阳市| 浮梁县| 肥乡县| 永靖县| 临海市| 安多县| 项城市| 鹤庆县| 抚顺市| 政和县| 丽水市|