單頁面和多頁面續集
阿新 • • 發佈:2020-10-07
單頁面和多頁面續集
一、元件化模組化
上集說到,我們希望views專注頁面渲染
我們將元件拆分出去,相對應的我們還可以將樣式程式碼,api請求等拆分,按需引入。
一、目錄結構
|_src |_assets |_js |_scanCompontent.js //webpack方法處理過多的import 引入 |_api |_apilist.js |_axios.js |_router |_index.js |_styles |_home |_index.scss |_about |_index.scss |_instance |_home |_index.vue |_main.js |_about |_index.vue |_main.js |_components |_home |_one.vue |_two.vue |_about |_about.vue |_views |_home.vue |_about.vue
二、方法介紹
webpack優化之一 main.js require.context(dir,boolean, reg) 資料夾路徑,是否搜尋子目錄,匹配檔案的正則 我們可以使用它遍歷自定義封裝的元件,迴圈註冊成全域性元件,我們就可以不用一一import const files = require.context('@/components',true,/\.vue$/) const modules = [] //modules在這別找不到了 說明: require.context()執行後files 返回一個函式webpackContext ƒ webpackContext(req) { var id = webpackContextResolve(req); return __webpack_require__(id); } 可以看到執行後又返回了一個__webpack_require__,這個__webpack_require__相當於require或者import,webpackContext還有第二個靜態方法keys和resolve,一個id屬性 我們著重看keys 試著輸出console.log(files.keys()) 輸出是地址陣列:["./four/Index.vue", "./one/alice.vue", "./one/bob.vue", "./one/cini.vue", "./one/deft.vue", "./three/Index.vue", "./two/Index.vue"] 這邊你可能還是不知道獲取到這些路徑有什麼用,我們繼續來看 試著遍歷這個陣列 files.keys().forEach(ele=>{ console.log(ele); //不用說你也知道是一個個路徑 試著將路徑放到files中 console.log(files(ele)) 輸出:Module{default: {…}, __esModule: true, Symbol(Symbol.toStringTag): "Module"} 實際上這正是我們要引入的元件 讓我們回想一下vue中怎麼註冊全域性元件 Vue.component(name,con) 那麼我們可以定義一個modules來存放這些將來成為全域性元件的東東,暫時收留一下它們 讓我們對名字做一些處理 let name = key.split('/').pop().replace(/.vue/g,""); let component = files(ele); modules.push({name,component}) }) 最後讓我們看以後modules是什麼樣的? 0: {name: "Index", component: Module} 1: {name: "alice", component: Module} 2: {name: "bob", component: Module} 3: {name: "cini", component: Module} 4: {name: "deft", component: Module} 5: {name: "Index", component: Module} 6: {name: "Index", component: Module} length: 7 __proto__: Array(0) 有了這些我們就可以將它們註冊為全域性元件了 modules.map(ele=>{ let {name,component:com} = ele Vue.component(name,com.default) }) 然後就是元件的使用了,就不多說了 <alice></alice> 實際上可以將這段程式碼引出去scanCompontent.js
https://www.webpackjs.com/guides/dependency-management/
二、多頁面中涉及的到的webpack處理
一、方法介紹
glob
npm i glob const glob = require('glob') glob("**/*.js",options,function(err,files){}) entry.js let titles = { a:xxx, b:xxx } function getEntry(globPath){ //執行全域性同步搜尋 let entries = {}, tmp, htmls = {}; glob.sync(globPath+'js').forEach(function(entry) { tmp = entry.split('/').splice(-3); entries[tmp[1]] = { entry, template: 'index.html', filename:tmp[1] + '.html', title:titles[tmp[1]] }; }); return entries; } let htmls = getEntry('./src/instance/**/*.'); // ' /**/* ' // 包含instance下的所有目錄的所有檔案, 包含任何目錄下面的目錄下的檔案 module.exports = htmls cmd中輸出 { about: { entry: './src/instance/about/main.js', template: 'index.html', filename: 'about.html', title: undefined }, home: { entry: './src/instance/home/main.js', template: 'index.html', filename: 'home.html', title: undefined } }
externals
externals
配置選項提供了「從輸出的 bundle 中排除依賴」的方法。相反,所建立的 bundle 依賴於那些存在於使用者環境(consumer's environment)中的依賴。
防止將某些 import
的包(package)打包到 bundle 中,而是在執行時(runtime)再去從外部獲取這些擴充套件依賴(external dependencies)。
index.html通過cdn的方式引入
const externals = {
jquery:'Jquery'
}
module.exports = externals;
plugins
首先plugins的外掛比較多,這邊就簡單介紹用到的
compression-webpack-plugin
壓縮webpack 外掛
npm install compression-webpack-plugin --save-dev
vue.config.js
const CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
plugins:[new CompressionPlugin({
filename: '[path].gz[query]', 檔名
algorithm: 'gzip', //壓縮演算法/功能
test: /\.(js|css|svg|woff|ttf|json|html)$/, /Include all assets that pass test assertion
threshold: 10240, //僅處理比10240位元組大的外掛
minRatio: 0.8, //僅壓縮比該比率更好的資產
deleteOriginalAssets: false //是不是刪除原來的origin assets
})],
}
uglifyjs-webpack-plugin
js壓縮
npm install uglifyjs-webpack-plugin --save-dev
module.exports = {
optimization: {
minimizer: [new UglifyJsPlugin()],
},
};
二、vue中webpack設定
調整webpack配置最簡單的方法就是在vue.config.js中的configureWebpack選項提供一個物件:
//vue.config.js
module.exports = {
configureWebpack:{
plugins:[
new CompressionPlugin()
]
}
}
如果你需要基於環境有條件地配置行為,或者想要直接修改配置,那就換成一個函式 (該函式會在環境變數被設定之後懶執行)。該方法的第一個引數會收到已經解析好的配置。在函式內,你可以直接修改配置,或者返回一個將會被合併的物件:
module.exports = {
configureWebpack:config=>{
if (process.env.NODE_ENV === 'production') {
// 為生產環境修改配置...
} else {
// 為開發環境修改配置...
}
}
}
module.exports = {
configureWebpack: (config) => {
config.externals = externals;
config.plugins = [...config.plugins,...plugins];
config.optimization = optimization;
},
pages:htmls,
publicPath: './',
outputDir: 'dist',
devServer: {
open: true,
hot:true
}
}