vue-loader 能根據 .vue 文件,導入一個vue組件。我這里從 vue-cli 的構建項目中抽取了vue-loader 一個小例子出來:vuedemo/demo02
vue-loader 自帶postcss的依賴,也就是說被引入的 .vue 組件中的css 會被postcss處理,但需要自己手動添加一個postcss的配置文件:
// .postcssrc.js
module.exports = {
"plugins": { "autoprefixer": {} } }
以上配置了自動添加瀏覽器前綴,能正常運行。
簡要介紹下 postcss:
PostCSS 的主要功能只有兩個:第一個就是前面提到的把 CSS 解析成 JavaScript 可以操作的 AST,第二個就是調用插件來處理 AST 並得到結果。以上就是使用的autoprefixer插件,處理的效果如下:
#content { display: flex; } // after #content { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; }
由於 CSS 規范的制定和完善一般需要花費比較長的時間,瀏覽器廠商在實現某個 CSS 新功能時,會使用特定的瀏覽器前綴來作為正式規范版本之前的實驗性實現。比如 Webkit 核心的瀏覽器使用-webkit-,微軟的 IE 使用-ms-。為了兼容不同瀏覽器的不同版本,在編寫 CSS 樣式規則聲明時通常需要添加額外的帶前綴的屬性
資料參考:
https://vuejs.org/v2/guide/installation.html
https://webpack.js.org/configuration/resolve/
vue的庫文件分為兩大類:compiler和runtime。前者用於把template(template選項以及 .vue 文件中template區域)編譯到render函數中,而后者僅僅支持vue框架的運行處理,不支持前者的模板轉換過程,運行時最終執行的都是render函數。
所以,如果按中不包含template,就可以僅僅引入runtime庫就可以了,否則要引入full(compiler + runtime)
對於以上倉庫中的例子,如果不在webpack配置文件中指定引入 full版本的文件 :
resolve: {
extensions: [".vue",".js",".json"], alias: { 'vue$': 'vue/dist/vue.js', } },
打包后運行就會出現這個錯誤:
[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
因為默認引入vue的是runtime版,不支持 .vue 文件中的template轉換。
https://cn.vuejs.org/v2/guide/render-function.html
https://cn.vuejs.org/v2/guide/deployment.html
使用vue單文件組件都是通過vue-loader來引入的,這里記錄一些細節
自動實現了template到render函數的轉換
在一個vue組件中,組件的html代碼可以通過template屬性或render函數來指定,兩者的區別在於,template會轉換為render函數來執行,也就是說最終執行的都是render函數。
所以在生產環境中,可以先進行編譯,這樣生產環境中運行就不再需要動態轉換,性能可以提高一些。
vue-loader默認做了這個轉換過程,打包后的bundle文件有如下代碼 :
//... "use strict"; var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c("div", { staticClass: "wrapper" }, [ _c("div", { staticClass: "container" }, [ _vm.loginPage ? _c( "form", { attrs: { action: "" }, on: { submit: function($event) { $event.preventDefault() _vm.login($event) } } }, // ....
.vue (單文件組件)中的template已經被轉換了。實現以上過程實際上是vue-loader 內 調用了vue-template-compiler 。在vue-loader/template-compiler/index.js 中有對vue-template-compiler 進行引用
處理css
.vue 文件中 style表內的樣式默認都是通過js動態寫入到head中,如果這個js較慢才執行,則屏幕可能出現閃屏現象,而且對瀏覽器緩存不友好。解決辦法是使用extract-text-webpack-plugin插件。
啟用scss
The vue config in webpack-simple works for
lang="scss"
(after installing sass-loader and node-sass), but it does not include the ExtractTextPlugin.
只需要安裝sass-loader 和 node-sass 之后在style標簽上添加一個lang="scss"即可