標籤:path value boot 還需要 window 目錄 comm blog sch
ProvidePlugin
module.export = { plugins: [ new webpack.ProvidePlugin({ $: ‘jquery‘, jQuery: ‘jquery‘, ‘window.jQuery‘: ‘jquery‘, ‘window.$‘: ‘jquery‘, }), ]}
rovidePlugin的機制是:當webpack載入到某個js模組裡,出現了未定義且名稱符合(字串完全符合)配置中key的變數時,會自動require配置中value所指定的js模組
使用ProvidePlugin還有個好處,就是,你自己寫的代碼裡,再!也!不!用!require!jQuery!啦!
延伸:
{
test: require.resolve(‘jquery‘), // 此loader配置項的目標是NPM中的jquery
loader: ‘expose?$!expose?jQuery‘, // 先把jQuery對象聲明成為全域變數`jQuery`,再通過管道進一步又聲明成為全域變數`$`
},
有了ProvidePlugin為嘛還需要expose-loader?
如果你所有的jQuery外掛程式都是用webpack來載入的話,的確用ProvidePlugin就足夠了;
不過總有那麼些需求是只能用<script>來載入的
webpack.optimize.CommonsChunkPlugin
new webpack.optimize.CommonsChunkPlugin({ name: ‘commons/commons‘, filename: ‘[name]/bundle.js‘, minChunks: 4,}),
抽取出所有通用的部分,參數:
- name: ‘commons/commons‘ : 給這個包含公用代碼的chunk命個名(唯一標識)
- chunks: 表示需要在哪些chunk(也可以理解為webpack配置中entry的每一項)裡尋找公用代碼進行打包。不設定此參數則預設提取範圍為所有的chunk
- filename: ‘[name]/bundle.js‘ :如何命名打包後生產的js檔案,也是可以用上[name]、[hash]、[chunkhash]這些變數的, 例子就是‘commons/commons/bundle.js‘了 (最終組建檔案的路徑是根據webpack配置中的ouput.path和上面CommonsChunkPlugin的filename參數來拼的)
- minChunks: 4, : 公用代碼的判斷標準:某個js模組被多少個chunk載入了才算是公用代碼
ExtractTextPlugin
new ExtractTextPlugin(‘[name]/styles.css‘),
抽取出chunk的css ,
ExtractTextPlugin的初始化參數不多,唯一的必填項是filename參數,也就是如何來命名產生的CSS檔案。跟webpack配置裡的output.filename參數類似,這ExtractTextPlugin的filename參數也允許使用變數,包括[id]、[name]和[contenthash];理論上來說如果只有一個chunk,那麼不用這些變數,寫死一個檔案名稱也是可以的,但由於我們要做的是多頁應用,必然存在多個chunk(至少每個entry都對應一個chunk啦)
在這裡配置的[name]對應的是chunk的name,在webpack配置中把各個entry的name都按index/index、index/login這樣的形式來設定了,那麼最後css的路徑就會像這樣:build/index/index/styles.css,跟chunk的js檔案放一塊了(js檔案的路徑形如build/index/index/entry.js)
備忘: 還要在css-loader , less-loader , postcss-loader 等關於樣式的loader 配置裡做相應的修改
{ test: /\.css$/, include: /bootstrap/, use: ExtractTextPlugin.extract([{ loader: ‘css-loader‘, }]),}
HtmlWebpackPlugin
var glob = require(‘glob‘);var path = require(‘path‘);var options = { cwd: ‘./src/pages‘, // 在pages目錄裡找 sync: true, // 這裡不能非同步,只能同步};var globInstance = new glob.Glob(‘!(_)*/!(_)*‘, options); // 考慮到多個頁面共用HTML等資源的情況,跳過以‘_‘開頭的目錄var pageArr = globInstance.found; // 一個數組,形如[‘index/index‘, ‘index/login‘, ‘alert/index‘]var configPlugins = [];pageArr.forEach((page) => { const htmlPlugin = new HtmlWebpackPlugin({ filename: `${page}/page.html`, template: path.resolve(dirVars.pagesDir, `./${page}/html.js`), // 意思是載入 page 下面的js , 和載入 commons/commons 目錄下的js chunks: [page, ‘commons/commons‘], hash: true, // 為靜態資源產生hash值 xhtml: true, }); configPlugins.push(htmlPlugin);});
產生html,參數:
- filename `${page}/page.html`, : 產生的檔案名稱字,多頁面就會有多個 HtmlWebpackPlugin ,通常使用迴圈產生一個數組
- template : path.resolve(dirVars.pagesDir, `./${page}/html.js`), 產生的html 基於的模板
- chunks : [ page, ‘commons/commons‘] : 意思是載入 變數page 和 commons/commons 目錄下的js
- hash: true : 為靜態資源產生hash值
webpack-webpackConfig-plugin 配置