手把手带你撸一遍vue-loader源码
前言
前面寫(xiě)過(guò)兩篇webpack實(shí)戰(zhàn)的文章:
- webpack實(shí)戰(zhàn)之(手把手教你從0開(kāi)始搭建一個(gè)vue項(xiàng)目)
- 手把手教你從0開(kāi)始搭建一個(gè)vue項(xiàng)目(完結(jié))
強(qiáng)烈建議小伙伴們?nèi)タ匆幌虑懊鎺讉€(gè)章節(jié)的內(nèi)容,
這一節(jié)我們研究一下vue-loader。
介紹
Vue Loader 是什么?
Vue Loader 是一個(gè) webpack 的 loader,它允許你以一種名為單文件組件 (SFCs)的格式撰寫(xiě) Vue 組件:
<template><div class="example">{{ msg }}</div> </template><script> export default {data () {return {msg: 'Hello world!'}} } </script><style> .example {color: red; } </style>Vue Loader 還提供了很多酷炫的特性:
- 允許為 Vue 組件的每個(gè)部分使用其它的 webpack loader,例如在 `` 的部分使用 Sass 和在 ` 的部分使用 Pug;
- 允許在一個(gè) .vue 文件中使用自定義塊,并對(duì)其運(yùn)用自定義的 loader 鏈;
- 使用 webpack loader 將 `` 和 ` 中引用的資源當(dāng)作模塊依賴來(lái)處理;
- 為每個(gè)組件模擬出 scoped CSS;
- 在開(kāi)發(fā)過(guò)程中使用熱重載來(lái)保持狀態(tài)。
簡(jiǎn)而言之,webpack 和 Vue Loader 的結(jié)合為你提供了一個(gè)現(xiàn)代、靈活且極其強(qiáng)大的前端工作流,來(lái)幫助撰寫(xiě) Vue.js 應(yīng)用。
以上內(nèi)容都是vue-loader官網(wǎng)的內(nèi)容,基礎(chǔ)用法大家可以自己去看vue-loader的官網(wǎng),我就不在這里詳細(xì)介紹了。
開(kāi)始
我們還是用之前章節(jié)的webpack-vue-demo項(xiàng)目做測(cè)試demo,大家可以直接clone。
我們首先看一下demo項(xiàng)目的入口文件src/main.ts:
import Vue from "vue"; // import App from "./app.vue"; import App from "./app.vue";new Vue({el: "#app",render: h => h(App) });可以看到,直接引用了一個(gè)app.vue組件,
src/app.vue:
<template><div class="app-container">{{ msg }}</div> </template><script lang="ts"> import { Vue, Component } from "vue-property-decorator";@Component export default class App extends Vue {msg = "hello world";user = {name: "yasin"};created(): void {// const name = this.user?.name;// console.log("name");} } </script><style scoped lang="scss"> .app-container {color: red; } </style>代碼很簡(jiǎn)單,就是一個(gè)普通的vue組件,然后輸出一個(gè)“hello world”,大家可以直接在項(xiàng)目根目錄執(zhí)行"npm run dev"命令來(lái)運(yùn)行項(xiàng)目。
ok,然后看一下webpack的配置文件webpack.config.js:
const path = require("path"); const config = new (require("webpack-chain"))(); const isDev = !!process.env.WEBPACK_DEV_SERVER; config.context(path.resolve(__dirname, ".")) //webpack上下文目錄為項(xiàng)目根目錄.entry("app") //入口文件名稱為app.add("./src/main.ts") //入口文件為./src/main.ts.end().output.path(path.join(__dirname,"./dist")) //webpack輸出的目錄為根目錄的dist目錄.filename("[name].[hash:8].js").end().resolve.extensions.add(".js").add(".jsx").add(".ts").add(".tsx").add(".vue") //配置以.js等結(jié)尾的文件當(dāng)模塊使用的時(shí)候都可以省略后綴.end().end().module.rule('js').test(/\.m?jsx?$/) //對(duì)mjs、mjsx、js、jsx文件進(jìn)行babel配置.exclude.add(filepath => {// Don't transpile node_modulesreturn /node_modules/.test(filepath)}).end().use("babel-loader").loader("babel-loader").end().end().rule("type-script").test(/\.tsx?$/) //loader加載的條件是ts或tsx后綴的文件.use("babel-loader").loader("babel-loader").end().use("ts-loader").loader("ts-loader").options({ //ts-loader相關(guān)配置transpileOnly: true, // disable type checker - we will use it in fork pluginappendTsSuffixTo: ['\\.vue$']}).end().end().rule("vue").test(/\.vue$/)// 匹配.vue文件.use("vue-loader").loader("vue-loader").end().end().rule("sass").test( /\.(sass|scss)$/)//sass和scss文件.use("extract-loader")//提取css樣式到單獨(dú)css文件.loader(require('mini-css-extract-plugin').loader).options({hmr: isDev //開(kāi)發(fā)環(huán)境開(kāi)啟熱載}).end().use("css-loader")//加載css模塊.loader("css-loader").end().use("postcss-loader")//處理css樣式.loader("postcss-loader").options( {config: {path: path.resolve(__dirname, "./postcss.config.js")}}).end().use("sass-loader")//sass語(yǔ)法轉(zhuǎn)css語(yǔ)法.loader("sass-loader").end().end().rule('eslint')//添加eslint-loader.exclude.add(/node_modules/)//校驗(yàn)的文件除node_modules以外.end().test(/\.(vue|(j|t)sx?)$/)//加載.vue、.js、.jsx、.ts、.tsx文件.use('eslint-loader').loader(require.resolve('eslint-loader')).options({emitWarning: true, //把eslint報(bào)錯(cuò)當(dāng)成webpack警告emitError: !isDev, //把eslint報(bào)錯(cuò)當(dāng)成webapck的錯(cuò)誤}).end().end().end().plugin("vue-loader-plugin")//vue-loader必須要添加vue-loader-plugin.use(require("vue-loader").VueLoaderPlugin,[]).end().plugin("html")// 添加html-webpack-plugin插件.use(require("html-webpack-plugin"),[{template: path.resolve(__dirname,"./public/index.html"), //指定模版文件chunks: ["runtime", "chunk-vendors", "chunk-common", "app"], //指定需要加載的chunksinject: "body" //指定script腳本注入的位置為body}]).end().plugin("extract-css")//提取css樣式到單獨(dú)css文件.use(require('mini-css-extract-plugin'), [{filename: "css/[name].css",chunkFilename: "css/[name].css"}]).end().plugin('fork-ts-checker') //配置fork-ts-checker.use(require('fork-ts-checker-webpack-plugin'), [{eslint: {files: './src/**/*.{ts,tsx,js,jsx,vue}' // required - same as command `eslint ./src/**/*.{ts,tsx,js,jsx} --ext .ts,.tsx,.js,.jsx`},typescript: {extensions: {vue: {enabled: true,compiler: "vue-template-compiler"},}}}]).end().devServer.host("0.0.0.0") //為了讓外部服務(wù)訪問(wèn).port(8090) //當(dāng)前端口號(hào).hot(true) //熱載.open(true) //開(kāi)啟頁(yè)面.overlay({warnings: false,errors: true}) //webpack錯(cuò)誤和警告信息顯示到頁(yè)面 config.when(!isDev,()=>{config.optimization.minimize(true).minimizer("terser").use(require("terser-webpack-plugin"),[{extractComments: false, //去除注釋terserOptions:{output: {comments: false //去除注釋}}}]); },()=>{config.devtool("eval-cheap-module-source-map"); }); config.optimization.splitChunks({cacheGroups: {vendors: { //分離入口文件引用node_modules的module(vue、@babel/xxx)name: `chunk-vendors`,test: /[\\/]node_modules[\\/]/,priority: -10,chunks: 'initial'},common: { //分離入口文件引用次數(shù)>=2的modulename: `chunk-common`,minChunks: 2,priority: -20,chunks: 'initial',reuseExistingChunk: true}}}).runtimeChunk("single"); //分離webpack的一些幫助函數(shù),比如webpackJSONP等等module.exports = config.toConfig();每一個(gè)配置項(xiàng)前面章節(jié)都有詳細(xì)介紹的,我就不一一解析了,我們繼續(xù)往下。
SFC
我們直接打開(kāi)src/app.vue文件:
<template><div class="app-container">{{ msg }}</div> </template><script lang="ts"> import { Vue, Component } from "vue-property-decorator";@Component export default class App extends Vue {msg = "hello world";user = {name: "yasin"};created(): void {// const name = this.user?.name;// console.log("name");} } </script><style scoped lang="scss"> .app-container {color: red; } </style>ok! 那么webpack是怎么加載我們的“.vue”結(jié)尾的文件呢?
因?yàn)槲覀冊(cè)趙ebpack.config.js中配置了loader,也就是說(shuō)是我們的loader去加載的".vue"文件,那么我們項(xiàng)目中的".vue"文件到底被哪些loader加載了呢?
我們直接利用IDE斷點(diǎn)看看,我們直接定位到webpack的“NormalModule”,然后當(dāng)webpack加載到app.vue模塊的時(shí)候,
node_modules/webpack/lib/NormalModule.js:
ok! 可以看到,當(dāng)webpack在加載app.vue模塊的時(shí)候,webpack使用的loader有(loader執(zhí)行順序?yàn)閺南峦?#xff09;:
我直接知道vue-loader的源碼,我這里的版本是“vue-loader@15.9.3”,
node_modules/vue-loader/lib/index.js:
const path = require('path') const hash = require('hash-sum') const qs = require('querystring') const plugin = require('./plugin') const selectBlock = require('./select') const loaderUtils = require('loader-utils') const { attrsToQuery } = require('./codegen/utils') const { parse } = require('@vue/component-compiler-utils') const genStylesCode = require('./codegen/styleInjection') const { genHotReloadCode } = require('./codegen/hotReload') const genCustomBlocksCode = require('./codegen/customBlocks') const componentNormalizerPath = require.resolve('./runtime/componentNormalizer') const { NS } = require('./plugin')let errorEmitted = falsefunction loadTemplateCompiler (loaderContext) {try {return require('vue-template-compiler')} catch (e) {if (/version mismatch/.test(e.toString())) {loaderContext.emitError(e)} else {loaderContext.emitError(new Error(`[vue-loader] vue-template-compiler must be installed as a peer dependency, ` +`or a compatible compiler implementation must be passed via options.`))}} }module.exports = function (source) {const loaderContext = thisif (!errorEmitted && !loaderContext['thread-loader'] && !loaderContext[NS]) {loaderContext.emitError(new Error(`vue-loader was used without the corresponding plugin. ` +`Make sure to include VueLoaderPlugin in your webpack config.`))errorEmitted = true}const stringifyRequest = r => loaderUtils.stringifyRequest(loaderContext, r)const {target,request,minimize,sourceMap,rootContext,resourcePath,resourceQuery} = loaderContextconst rawQuery = resourceQuery.slice(1)const inheritQuery = `&${rawQuery}`const incomingQuery = qs.parse(rawQuery)const options = loaderUtils.getOptions(loaderContext) || {}const isServer = target === 'node'const isShadow = !!options.shadowModeconst isProduction = options.productionMode || minimize || process.env.NODE_ENV === 'production'const filename = path.basename(resourcePath)const context = rootContext || process.cwd()const sourceRoot = path.dirname(path.relative(context, resourcePath))const descriptor = parse({source,compiler: options.compiler || loadTemplateCompiler(loaderContext),filename,sourceRoot,needMap: sourceMap})// if the query has a type field, this is a language block request// e.g. foo.vue?type=template&id=xxxxx// and we will return earlyif (incomingQuery.type) {return selectBlock(descriptor,loaderContext,incomingQuery,!!options.appendExtension)}// module id for scoped CSS & hot-reloadconst rawShortFilePath = path.relative(context, resourcePath).replace(/^(\.\.[\/\\])+/, '')const shortFilePath = rawShortFilePath.replace(/\\/g, '/') + resourceQueryconst id = hash(isProduction? (shortFilePath + '\n' + source): shortFilePath)// feature informationconst hasScoped = descriptor.styles.some(s => s.scoped)const hasFunctional = descriptor.template && descriptor.template.attrs.functionalconst needsHotReload = (!isServer &&!isProduction &&(descriptor.script || descriptor.template) &&options.hotReload !== false)// templatelet templateImport = `var render, staticRenderFns`let templateRequestif (descriptor.template) {const src = descriptor.template.src || resourcePathconst idQuery = `&id=${id}`const scopedQuery = hasScoped ? `&scoped=true` : ``const attrsQuery = attrsToQuery(descriptor.template.attrs)const query = `?vue&type=template${idQuery}${scopedQuery}${attrsQuery}${inheritQuery}`const request = templateRequest = stringifyRequest(src + query)templateImport = `import { render, staticRenderFns } from ${request}`}// scriptlet scriptImport = `var script = {}`if (descriptor.script) {const src = descriptor.script.src || resourcePathconst attrsQuery = attrsToQuery(descriptor.script.attrs, 'js')const query = `?vue&type=script${attrsQuery}${inheritQuery}`const request = stringifyRequest(src + query)scriptImport = (`import script from ${request}\n` +`export * from ${request}` // support named exports)}// styleslet stylesCode = ``if (descriptor.styles.length) {stylesCode = genStylesCode(loaderContext,descriptor.styles,id,resourcePath,stringifyRequest,needsHotReload,isServer || isShadow // needs explicit injection?)}let code = ` ${templateImport} ${scriptImport} ${stylesCode}/* normalize component */ import normalizer from ${stringifyRequest(`!${componentNormalizerPath}`)} var component = normalizer(script,render,staticRenderFns,${hasFunctional ? `true` : `false`},${/injectStyles/.test(stylesCode) ? `injectStyles` : `null`},${hasScoped ? JSON.stringify(id) : `null`},${isServer ? JSON.stringify(hash(request)) : `null`}${isShadow ? `,true` : ``} )`.trim() + `\n`if (descriptor.customBlocks && descriptor.customBlocks.length) {code += genCustomBlocksCode(descriptor.customBlocks,resourcePath,resourceQuery,stringifyRequest)}if (needsHotReload) {code += `\n` + genHotReloadCode(id, hasFunctional, templateRequest)}// Expose filename. This is used by the devtools and Vue runtime warnings.if (!isProduction) {// Expose the file's full path in development, so that it can be opened// from the devtools.code += `\ncomponent.options.__file = ${JSON.stringify(rawShortFilePath.replace(/\\/g, '/'))}`} else if (options.exposeFilename) {// Libraries can opt-in to expose their components' filenames in production builds.// For security reasons, only expose the file's basename in production.code += `\ncomponent.options.__file = ${JSON.stringify(filename)}`}code += `\nexport default component.exports`return code }module.exports.VueLoaderPlugin = plugin代碼有點(diǎn)多,不過(guò)不要慌,我們一步一步來(lái),還記得我們之前實(shí)戰(zhàn)的配置vue-loader的時(shí)候,如果不配置VueLoaderPlugin的話,webpack就會(huì)直接報(bào)錯(cuò)?ok,那我們就看一下VueLoaderPlugin到底干了什么,
node_modules/vue-loader/lib/plugin.js:
const webpack = require('webpack') let VueLoaderPlugin = nullif (webpack.version && webpack.version[0] > 4) {// webpack5 and upperVueLoaderPlugin = require('./plugin-webpack5') } else {// webpack4 and lowerVueLoaderPlugin = require('./plugin-webpack4') }module.exports = VueLoaderPlugin我們這里用的webpack版本是"4.44.0",所以我們直接就看“plugin-webpack4”了(其實(shí)這里的5.0區(qū)別也就是rule的獲取不一樣罷了,因?yàn)閣ebpack5.0添加了depend參數(shù)等等),
node_modules/vue-loader/lib/plugin-webpack4.js:
const qs = require('querystring') const RuleSet = require('webpack/lib/RuleSet')const id = 'vue-loader-plugin' const NS = 'vue-loader'class VueLoaderPlugin {apply (compiler) {// add NS marker so that the loader can detect and report missing pluginif (compiler.hooks) {// webpack 4compiler.hooks.compilation.tap(id, compilation => {const normalModuleLoader = compilation.hooks.normalModuleLoadernormalModuleLoader.tap(id, loaderContext => {loaderContext[NS] = true})})} else {// webpack < 4compiler.plugin('compilation', compilation => {compilation.plugin('normal-module-loader', loaderContext => {loaderContext[NS] = true})})}// use webpack's RuleSet utility to normalize user rulesconst rawRules = compiler.options.module.rulesconst { rules } = new RuleSet(rawRules)// find the rule that applies to vue fileslet vueRuleIndex = rawRules.findIndex(createMatcher(`foo.vue`))if (vueRuleIndex < 0) {vueRuleIndex = rawRules.findIndex(createMatcher(`foo.vue.html`))}const vueRule = rules[vueRuleIndex]if (!vueRule) {throw new Error(`[VueLoaderPlugin Error] No matching rule for .vue files found.\n` +`Make sure there is at least one root-level rule that matches .vue or .vue.html files.`)}if (vueRule.oneOf) {throw new Error(`[VueLoaderPlugin Error] vue-loader 15 currently does not support vue rules with oneOf.`)}// get the normlized "use" for vue filesconst vueUse = vueRule.use// get vue-loader optionsconst vueLoaderUseIndex = vueUse.findIndex(u => {return /^vue-loader|(\/|\\|@)vue-loader/.test(u.loader)})if (vueLoaderUseIndex < 0) {throw new Error(`[VueLoaderPlugin Error] No matching use for vue-loader is found.\n` +`Make sure the rule matching .vue files include vue-loader in its use.`)}// make sure vue-loader options has a known ident so that we can share// options by reference in the template-loader by using a ref query like// template-loader??vue-loader-optionsconst vueLoaderUse = vueUse[vueLoaderUseIndex]vueLoaderUse.ident = 'vue-loader-options'vueLoaderUse.options = vueLoaderUse.options || {}// for each user rule (expect the vue rule), create a cloned rule// that targets the corresponding language blocks in *.vue files.const clonedRules = rules.filter(r => r !== vueRule).map(cloneRule)// global pitcher (responsible for injecting template compiler loader & CSS// post loader)const pitcher = {loader: require.resolve('./loaders/pitcher'),resourceQuery: query => {const parsed = qs.parse(query.slice(1))return parsed.vue != null},options: {cacheDirectory: vueLoaderUse.options.cacheDirectory,cacheIdentifier: vueLoaderUse.options.cacheIdentifier}}// replace original rulescompiler.options.module.rules = [pitcher,...clonedRules,...rules]} }function createMatcher (fakeFile) {return (rule, i) => {// #1201 we need to skip the `include` check when locating the vue ruleconst clone = Object.assign({}, rule)delete clone.includeconst normalized = RuleSet.normalizeRule(clone, {}, '')return (!rule.enforce &&normalized.resource &&normalized.resource(fakeFile))} }function cloneRule (rule) {const { resource, resourceQuery } = rule// Assuming `test` and `resourceQuery` tests are executed in series and// synchronously (which is true based on RuleSet's implementation), we can// save the current resource being matched from `test` so that we can access// it in `resourceQuery`. This ensures when we use the normalized rule's// resource check, include/exclude are matched correctly.let currentResourceconst res = Object.assign({}, rule, {resource: {test: resource => {currentResource = resourcereturn true}},resourceQuery: query => {const parsed = qs.parse(query.slice(1))if (parsed.vue == null) {return false}if (resource && parsed.lang == null) {return false}const fakeResourcePath = `${currentResource}.${parsed.lang}`if (resource && !resource(fakeResourcePath)) {return false}if (resourceQuery && !resourceQuery(query)) {return false}return true}})if (rule.rules) {res.rules = rule.rules.map(cloneRule)}if (rule.oneOf) {res.oneOf = rule.oneOf.map(cloneRule)}return res }VueLoaderPlugin.NS = NS module.exports = VueLoaderPlugin又是很長(zhǎng)一段代碼!!
我們直接找到這么一段代碼:
class VueLoaderPlugin {apply (compiler) {...// use webpack's RuleSet utility to normalize user rulesconst rawRules = compiler.options.module.rulesconst { rules } = new RuleSet(rawRules)// find the rule that applies to vue fileslet vueRuleIndex = rawRules.findIndex(createMatcher(`foo.vue`))if (vueRuleIndex < 0) {vueRuleIndex = rawRules.findIndex(createMatcher(`foo.vue.html`))}const vueRule = rules[vueRuleIndex]if (!vueRule) {throw new Error(`[VueLoaderPlugin Error] No matching rule for .vue files found.\n` +`Make sure there is at least one root-level rule that matches .vue or .vue.html files.`)}// get the normlized "use" for vue filesconst vueUse = vueRule.use// get vue-loader optionsconst vueLoaderUseIndex = vueUse.findIndex(u => {return /^vue-loader|(\/|\\|@)vue-loader/.test(u.loader)})// make sure vue-loader options has a known ident so that we can share// options by reference in the template-loader by using a ref query like// template-loader??vue-loader-optionsconst vueLoaderUse = vueUse[vueLoaderUseIndex]...首先找到了我們配置在webpack中的vueLoaderUse,也就是我們配置的“vue-loader”,然后給默認(rèn)webpack的loader配置中添加了一個(gè)叫“pitcher”的loader:
...const vueLoaderUse = vueUse[vueLoaderUseIndex]vueLoaderUse.ident = 'vue-loader-options'vueLoaderUse.options = vueLoaderUse.options || {}// for each user rule (expect the vue rule), create a cloned rule// that targets the corresponding language blocks in *.vue files.const clonedRules = rules.filter(r => r !== vueRule).map(cloneRule)// global pitcher (responsible for injecting template compiler loader & CSS// post loader)const pitcher = {loader: require.resolve('./loaders/pitcher'),resourceQuery: query => {const parsed = qs.parse(query.slice(1))return parsed.vue != null},options: {cacheDirectory: vueLoaderUse.options.cacheDirectory,cacheIdentifier: vueLoaderUse.options.cacheIdentifier}}// replace original rulescompiler.options.module.rules = [pitcher,...clonedRules,...rules] ...我們看一下“pitcher-loader”干了什么?
我們先看一下默認(rèn)loader的執(zhí)行順序,比如我們的配置是這樣的:
odule.exports = {//...module: {rules: [{//...use: ['a-loader','b-loader','c-loader']}]} };然后webpack默認(rèn)加載順序是這樣的:
|- a-loader `pitch` //如果a-loader有pitch函數(shù)就會(huì)先加載a-loader的pitch函數(shù)|- b-loader `pitch`|- c-loader `pitch`|- requested module is picked up as a dependency|- c-loader normal execution|- b-loader normal execution |- a-loader normal execution但凡有一個(gè)loader是有pitch函數(shù)并且pitch函數(shù)有返回值的話,順序又不一樣了,比如當(dāng)a-loader的pitch函數(shù)有返回值的時(shí)候,
a-loader:
module.exports = function(content) {return someSyncOperation(content); }; module.exports.pitch = function(remainingRequest, precedingRequest, data) {if (someCondition()) {return 'module.exports = require(' + JSON.stringify('-!' + remainingRequest) + ');';} };執(zhí)行順序就變成了:
|- a-loader `pitch`當(dāng)a-loader的pitch函數(shù)有返回值的時(shí)候,就只會(huì)執(zhí)行排在a-loader之后的loader,但是在我們當(dāng)前配置中a-loader之后已經(jīng)沒(méi)有l(wèi)oader了,所以會(huì)直接返回:
return 'module.exports = require(' + JSON.stringify('-!' + remainingRequest) + ');';具體大家可以可以看一下webpack官網(wǎng),或者可以看看網(wǎng)上的這篇文章[揭秘webpack loader](https://segmentfault.com/a/1190000021657031),借用下他文章的兩幅圖:
當(dāng)有pitch返回值的時(shí)候,比如loader2的pitch函數(shù)有返回值了:
好吧,我簡(jiǎn)單的帶大家看一下webpack源碼~
還記得我們文章一開(kāi)始的斷點(diǎn)嗎?
當(dāng)webpack需要加載某個(gè)模塊的時(shí)候(app.vue),會(huì)先執(zhí)行NormalModule的doBuild方法,
node_modules/webpack/lib/NormalModule.js:
const { getContext, runLoaders } = require("loader-runner"); ... doBuild(options, compilation, resolver, fs, callback) {const loaderContext = this.createLoaderContext(resolver,options,compilation,fs);runLoaders({resource: this.resource, //當(dāng)前app.vue文件位置loaders: this.loaders, //加載app.vue的所有l(wèi)oadercontext: loaderContext, //loader上線文對(duì)象readResource: fs.readFile.bind(fs) //當(dāng)前webpack文件系統(tǒng)},...ok,可以看到之后就是執(zhí)行了runLoaders方法,webpack直接把runLoaders方法放到了一個(gè)叫“l(fā)oader-runner”的第三方依賴中,
node_modules/loader-runner/lib/LoaderRunner.js:
... exports.runLoaders = function runLoaders(options, callback) {// read optionsvar resource = options.resource || "";var loaders = options.loaders || [];iteratePitchingLoaders(processOptions, loaderContext, function(err, result) {....});...代碼有點(diǎn)多,我們直接看重點(diǎn),我們看到runLoaders方法中又執(zhí)行了一個(gè)叫iteratePitchingLoaders的方法:
function iteratePitchingLoaders(options, loaderContext, callback) {// abort after last loaderif(loaderContext.loaderIndex >= loaderContext.loaders.length)return processResource(options, loaderContext, callback);var currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex];// iterateif(currentLoaderObject.pitchExecuted) {loaderContext.loaderIndex++;return iteratePitchingLoaders(options, loaderContext, callback);}// load loader moduleloadLoader(currentLoaderObject, function(err) {if(err) {loaderContext.cacheable(false);return callback(err);}var fn = currentLoaderObject.pitch;currentLoaderObject.pitchExecuted = true;if(!fn) return iteratePitchingLoaders(options, loaderContext, callback);runSyncOrAsync(fn,loaderContext, [loaderContext.remainingRequest, loaderContext.previousRequest, currentLoaderObject.data = {}],function(err) {if(err) return callback(err);var args = Array.prototype.slice.call(arguments, 1);if(args.length > 0) {loaderContext.loaderIndex--;iterateNormalLoaders(options, loaderContext, args, callback);} else {iteratePitchingLoaders(options, loaderContext, callback);}});}); }ok, 這里代碼我們就不詳細(xì)解析了,小伙伴自己去斷點(diǎn)跑跑就ok了,還是很容易看懂的,翻譯過(guò)后的邏輯就是我們前面說(shuō)的那樣:
比如我們的配置是這樣的:
odule.exports = {//...module: {rules: [{//...use: ['a-loader','b-loader','c-loader']}]} };然后webpack默認(rèn)加載順序是這樣的:
|- a-loader `pitch` //如果a-loader有pitch函數(shù)就會(huì)先加載a-loader的pitch函數(shù)|- b-loader `pitch`|- c-loader `pitch`|- requested module is picked up as a dependency|- c-loader normal execution|- b-loader normal execution |- a-loader normal executionok!又說(shuō)了那么多webpack-loader的知識(shí),我們還是回到我們的vue-loader,前面說(shuō)了vue-loader的VueLoaderPlugin給我們默認(rèn)loaders上面又添加了一個(gè)叫“pitcher-loader”的配置,
node_modules/vue-loader/lib/plugin-webpack4.js:
...const pitcher = {loader: require.resolve('./loaders/pitcher'),resourceQuery: query => {const parsed = qs.parse(query.slice(1))return parsed.vue != null},options: {cacheDirectory: vueLoaderUse.options.cacheDirectory,cacheIdentifier: vueLoaderUse.options.cacheIdentifier}}// replace original rulescompiler.options.module.rules = [pitcher,...clonedRules,...rules] ...node_modules/vue-loader/lib/loaders/pitcher.js:
... module.exports = code => code// This pitching loader is responsible for intercepting all vue block requests // and transform it into appropriate requests. module.exports.pitch = function (remainingRequest) {const options = loaderUtils.getOptions(this)const { cacheDirectory, cacheIdentifier } = optionsconst query = qs.parse(this.resourceQuery.slice(1))let loaders = this.loaders//過(guò)濾掉eslint-loaderif (query.type) {// if this is an inline block, since the whole file itself is being linted,// remove eslint-loader to avoid duplicate linting.if (/\.vue$/.test(this.resourcePath)) {loaders = loaders.filter(l => !isESLintLoader(l))} else {// This is a src import. Just make sure there's not more than 1 instance// of eslint present.loaders = dedupeESLintLoader(loaders)}}// 過(guò)濾掉自己loaders = loaders.filter(isPitcher)// 過(guò)濾掉一些null-loaderif (loaders.some(isNullLoader)) {return}const genRequest = loaders => {// Important: dedupe since both the original rule// and the cloned rule would match a source import request.// also make sure to dedupe based on loader path.// assumes you'd probably never want to apply the same loader on the same// file twice.// Exception: in Vue CLI we do need two instances of postcss-loader// for user config and inline minification. So we need to dedupe baesd on// path AND query to be safe.const seen = new Map()const loaderStrings = []loaders.forEach(loader => {const identifier = typeof loader === 'string'? loader: (loader.path + loader.query)const request = typeof loader === 'string' ? loader : loader.requestif (!seen.has(identifier)) {seen.set(identifier, true)// loader.request contains both the resolved loader path and its options// query (e.g. ??ref-0)loaderStrings.push(request)}})return loaderUtils.stringifyRequest(this, '-!' + [...loaderStrings,this.resourcePath + this.resourceQuery].join('!'))}// Inject style-post-loader before css-loader for scoped CSS and trimmingif (query.type === `style`) {const cssLoaderIndex = loaders.findIndex(isCSSLoader)if (cssLoaderIndex > -1) {const afterLoaders = loaders.slice(0, cssLoaderIndex + 1)const beforeLoaders = loaders.slice(cssLoaderIndex + 1)const request = genRequest([...afterLoaders,stylePostLoaderPath,...beforeLoaders])// console.log(request)return `import mod from ${request}; export default mod; export * from ${request}`}}// for templates: inject the template compiler & optional cacheif (query.type === `template`) {const path = require('path')const cacheLoader = cacheDirectory && cacheIdentifier? [`${require.resolve('cache-loader')}?${JSON.stringify({// For some reason, webpack fails to generate consistent hash if we// use absolute paths here, even though the path is only used in a// comment. For now we have to ensure cacheDirectory is a relative path.cacheDirectory: (path.isAbsolute(cacheDirectory)? path.relative(process.cwd(), cacheDirectory): cacheDirectory).replace(/\\/g, '/'),cacheIdentifier: hash(cacheIdentifier) + '-vue-loader-template'})}`]: []const preLoaders = loaders.filter(isPreLoader)const postLoaders = loaders.filter(isPostLoader)const request = genRequest([...cacheLoader,...postLoaders,templateLoaderPath + `??vue-loader-options`,...preLoaders])// console.log(request)// the template compiler uses esm exportsreturn `export * from ${request}`}// if a custom block has no other matching loader other than vue-loader itself// or cache-loader, we should ignore itif (query.type === `custom` && shouldIgnoreCustomBlock(loaders)) {return ``}// When the user defines a rule that has only resourceQuery but no test,// both that rule and the cloned rule will match, resulting in duplicated// loaders. Therefore it is necessary to perform a dedupe here.const request = genRequest(loaders)return `import mod from ${request}; export default mod; export * from ${request}` }ok,我們先放一放這個(gè)“pitcher-loader”😂
在文章一開(kāi)始的時(shí)候還記得我們的斷點(diǎn)嗎?當(dāng)webpack在加載app.vue模塊的時(shí)候,webpack使用的loader有(loader執(zhí)行順序?yàn)閺南峦?#xff09;:
ok,我們先直接看一下當(dāng)我們的app.vue文件:
<template><div class="app-container">{{ msg }}</div> </template><script lang="ts"> import { Vue, Component } from "vue-property-decorator";@Component export default class App extends Vue {msg = "hello world";user = {name: "yasin"};created(): void {// const name = this.user?.name;// console.log("name");} } </script><style scoped lang="scss"> .app-container {color: red; } </style>經(jīng)過(guò)vue-loader后變成什么樣了?
import { render, staticRenderFns } from "./app.vue?vue&type=template&id=5ef48958&scoped=true&" import script from "./app.vue?vue&type=script&lang=ts&" export * from "./app.vue?vue&type=script&lang=ts&" import style0 from "./app.vue?vue&type=style&index=0&id=5ef48958&scoped=true&lang=scss&"/* normalize component */ import normalizer from "!../node_modules/vue-loader/lib/runtime/componentNormalizer.js" var component = normalizer(script,render,staticRenderFns,false,null,"5ef48958",null)/* hot reload */ if (module.hot) {var api = require("/Users/ocj1/doc/h5/study/webpack/webpack-vue-demo/node_modules/vue-hot-reload-api/dist/index.js")api.install(require('vue'))if (api.compatible) {module.hot.accept()if (!api.isRecorded('5ef48958')) {api.createRecord('5ef48958', component.options)} else {api.reload('5ef48958', component.options)}module.hot.accept("./app.vue?vue&type=template&id=5ef48958&scoped=true&", function () {api.rerender('5ef48958', {render: render,staticRenderFns: staticRenderFns})})} } component.options.__file = "src/app.vue" export default component.exportsok, 可以看到,我們的模版代碼:
<template><div class="app-container">{{ msg }}</div> </template>第一次經(jīng)過(guò)vue-loader變成了:
import { render, staticRenderFns } from "./app.vue?vue&type=template&id=5ef48958&scoped=true&"然后我們的script代碼:
<script lang="ts"> import { Vue, Component } from "vue-property-decorator";@Component export default class App extends Vue {msg = "hello world";user = {name: "yasin"};created(): void {// const name = this.user?.name;// console.log("name");} } </script>第一次經(jīng)過(guò)vue-loader變成了:
import script from "./app.vue?vue&type=script&lang=ts&"我們的style模塊代碼:
<style scoped lang="scss"> .app-container {color: red; } </style>第一次經(jīng)過(guò)vue-loader變成了:
import style0 from "./app.vue?vue&type=style&index=0&id=5ef48958&scoped=true&lang=scss&"然后這幾個(gè)的值傳給了一個(gè)叫“normalizer”的方法:
/* normalize component */ import normalizer from "!../node_modules/vue-loader/lib/runtime/componentNormalizer.js" var component = normalizer(script,render,staticRenderFns,false,null,"5ef48958",null)最后我們的app.vue經(jīng)過(guò)vue-loader后導(dǎo)出了一個(gè)vue組件:
export default component.exportsok,我們看一下component返回的是不是一個(gè)vue組件呢?
我們直接找到“!../node_modules/vue-loader/lib/runtime/componentNormalizer.js”文件:
/* globals __VUE_SSR_CONTEXT__ */// IMPORTANT: Do NOT use ES2015 features in this file (except for modules). // This module is a runtime utility for cleaner component module output and will // be included in the final webpack user bundle.export default function normalizeComponent (scriptExports,render,staticRenderFns,functionalTemplate,injectStyles,scopeId,moduleIdentifier, /* server only */shadowMode /* vue-cli only */ ) {// Vue.extend constructor export interopvar options = typeof scriptExports === 'function'? scriptExports.options: scriptExports// render functionsif (render) {options.render = renderoptions.staticRenderFns = staticRenderFnsoptions._compiled = true}// functional templateif (functionalTemplate) {options.functional = true}// scopedIdif (scopeId) {options._scopeId = 'data-v-' + scopeId}var hookif (moduleIdentifier) { // server buildhook = function (context) {// 2.3 injectioncontext =context || // cached call(this.$vnode && this.$vnode.ssrContext) || // stateful(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional// 2.2 with runInNewContext: trueif (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {context = __VUE_SSR_CONTEXT__}// inject component stylesif (injectStyles) {injectStyles.call(this, context)}// register component module identifier for async chunk inferrenceif (context && context._registeredComponents) {context._registeredComponents.add(moduleIdentifier)}}// used by ssr in case component is cached and beforeCreate// never gets calledoptions._ssrRegister = hook} else if (injectStyles) {hook = shadowMode? function () {injectStyles.call(this,(options.functional ? this.parent : this).$root.$options.shadowRoot)}: injectStyles}if (hook) {if (options.functional) {// for template-only hot-reload because in that case the render fn doesn't// go through the normalizeroptions._injectStyles = hook// register for functional component in vue filevar originalRender = options.renderoptions.render = function renderWithStyleInjection (h, context) {hook.call(context)return originalRender(h, context)}} else {// inject component registration as beforeCreate hookvar existing = options.beforeCreateoptions.beforeCreate = existing? [].concat(existing, hook): [hook]}}return {exports: scriptExports,options: options} }ok,這里代碼還是很容易看懂的,以我們app.vue為例,最后componentNormalizer會(huì)返回一個(gè):
{exports: {render(h){var _vm = thisvar _h = _vm.$createElementvar _c = _vm._self._c || _hreturn _c("div", { staticClass: "app-container" }, [_vm._v(_vm._s(_vm.msg))])},data:{msg: "hello world"},beforeCreate:[...hook]},options: ...}我這里只是簡(jiǎn)單的列了一下哈,后面我們會(huì)具體分析到,也就是說(shuō)componentNormalizer會(huì)把我們的app.vue模版文件解析成一個(gè)普通的vue組件。
ok,我們的app.vue文件第一次被vue-loader解析后的代碼是這樣的:
import { render, staticRenderFns } from "./app.vue?vue&type=template&id=5ef48958&scoped=true&" import script from "./app.vue?vue&type=script&lang=ts&" export * from "./app.vue?vue&type=script&lang=ts&" import style0 from "./app.vue?vue&type=style&index=0&id=5ef48958&scoped=true&lang=scss&"/* normalize component */ import normalizer from "!../node_modules/vue-loader/lib/runtime/componentNormalizer.js" var component = normalizer(script,render,staticRenderFns,false,null,"5ef48958",null)/* hot reload */ if (module.hot) {var api = require("/Users/ocj1/doc/h5/study/webpack/webpack-vue-demo/node_modules/vue-hot-reload-api/dist/index.js")api.install(require('vue'))if (api.compatible) {module.hot.accept()if (!api.isRecorded('5ef48958')) {api.createRecord('5ef48958', component.options)} else {api.reload('5ef48958', component.options)}module.hot.accept("./app.vue?vue&type=template&id=5ef48958&scoped=true&", function () {api.rerender('5ef48958', {render: render,staticRenderFns: staticRenderFns})})} } component.options.__file = "src/app.vue" export default component.exports可以看到,解析完了的vue-loader里面又引用了app.vue文件,比如我們模版轉(zhuǎn)換過(guò)后的代碼:
import { render, staticRenderFns } from "./app.vue?vue&type=template&id=5ef48958&scoped=true&"所以當(dāng)webpack又執(zhí)行到這一行代碼的時(shí)候,我們看一下webpack默認(rèn)又用什么樣的loader去加載它呢?
ok, 可以看到,會(huì)有三個(gè)loader去加載"./app.vue?vue&type=template&id=5ef48958&scoped=true&"模塊(從下往上):
ok, 還記得我們前面說(shuō)的loader執(zhí)行順序嗎?
|- a-loader `pitch` //如果a-loader有pitch函數(shù)就會(huì)先加載a-loader的pitch函數(shù)|- b-loader `pitch`|- c-loader `pitch`|- requested module is picked up as a dependency|- c-loader normal execution|- b-loader normal execution |- a-loader normal execution我們這里的順序?yàn)?#xff1a;
|-xxx/node_modules/vue-loader/lib/loaders/pitcher.js `pitch`|-vue-loader `pitch`|-eslint-loader `pitch`|- requested module is picked up as a dependency|-eslint-loader normal execution|-vue-loader normal execution |-xxx/node_modules/vue-loader/lib/loaders/pitcher.js normal executionok, 如果當(dāng)“xxx/node_modules/vue-loader/lib/loaders/pitcher.js”的pitch函數(shù)有返回值時(shí),會(huì)執(zhí)行排在pitcher-loader之前的loader,但是我們可以發(fā)現(xiàn),排在pitcher-loader之前已經(jīng)沒(méi)有l(wèi)oader了,所以會(huì)直接返回pitcher-loader的pitch函數(shù)返回的內(nèi)容,我們來(lái)看看“xxx/node_modules/vue-loader/lib/loaders/pitcher.js” loader的pitch方法到底返回了什么?
node_modules/vue-loader/lib/loaders/pitcher.js:
module.exports.pitch = function (remainingRequest) {...// for templates: inject the template compiler & optional cacheif (query.type === `template`) {const path = require('path')const cacheLoader = cacheDirectory && cacheIdentifier? [`${require.resolve('cache-loader')}?${JSON.stringify({// For some reason, webpack fails to generate consistent hash if we// use absolute paths here, even though the path is only used in a// comment. For now we have to ensure cacheDirectory is a relative path.cacheDirectory: (path.isAbsolute(cacheDirectory)? path.relative(process.cwd(), cacheDirectory): cacheDirectory).replace(/\\/g, '/'),cacheIdentifier: hash(cacheIdentifier) + '-vue-loader-template'})}`]: []const preLoaders = loaders.filter(isPreLoader)const postLoaders = loaders.filter(isPostLoader)const request = genRequest([...cacheLoader,...postLoaders,templateLoaderPath + `??vue-loader-options`,...preLoaders])// console.log(request)// the template compiler uses esm exportsreturn `export * from ${request}`}...ok,也就是說(shuō)當(dāng)我們的這一行代碼:
import { render, staticRenderFns } from "./app.vue?vue&type=template&id=5ef48958&scoped=true&"經(jīng)過(guò)“node_modules/vue-loader/lib/loaders/pitcher.js”后會(huì)變成什么樣呢?
export * from "-!../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../node_modules/vue-loader/lib/index.js??vue-loader-options!./app.vue?vue&type=template&id=5ef48958&scoped=true&"ok,可以看到又是直接導(dǎo)入app.vue,然后讓:
這兩個(gè)loader去加載app.vue。
這里再說(shuō)幾個(gè)webpack中的知識(shí):
loader分為:
- pre: 前置loader
- normal: 普通loader
- inline: 內(nèi)聯(lián)loader
- post: 后置loade
執(zhí)行順序?yàn)?#xff1a;pre > normal > inline > post
內(nèi)聯(lián) loader 可以通過(guò)添加不同前綴,跳過(guò)其他類型 loader(從右至左)。
- ! 跳過(guò) normal loader。
- -! 跳過(guò) pre 和 normal loader。
- !! 跳過(guò) pre、 normal 和 post loader。
所以針對(duì)這里的:
export * from "-!../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../node_modules/vue-loader/lib/index.js??vue-loader-options!./app.vue?vue&type=template&id=5ef48958&scoped=true&"首先執(zhí)行的是"…/node_modules/vue-loader/lib/index.js??vue-loader-options!./app.vue?vue&type=template&id=5ef48958&scoped=true&",“??vue-loader-options!./app.vue?vue&type=template&id=5ef48958&scoped=true&”是vue-loader的參數(shù),這次我們看一下vue-loader會(huì)把我們的app.vue轉(zhuǎn)成什么樣子呢?
node_modules/vue-loader/lib/index.js
module.exports = function (source) { ... if (incomingQuery.type) {return selectBlock(descriptor,loaderContext,incomingQuery,!!options.appendExtension)}可以看到,這一次我們的loader是帶有type=template參數(shù)的,所以進(jìn)了vue-loader的selectBlock方法,
node_modules/vue-loader/lib/select.js:
module.exports = function selectBlock (descriptor,loaderContext,query,appendExtension ) {// templateif (query.type === `template`) {if (appendExtension) {loaderContext.resourcePath += '.' + (descriptor.template.lang || 'html')}loaderContext.callback(null,descriptor.template.content,descriptor.template.map)return}// scriptif (query.type === `script`) {if (appendExtension) {loaderContext.resourcePath += '.' + (descriptor.script.lang || 'js')}loaderContext.callback(null,descriptor.script.content,descriptor.script.map)return}// stylesif (query.type === `style` && query.index != null) {const style = descriptor.styles[query.index]if (appendExtension) {loaderContext.resourcePath += '.' + (style.lang || 'css')}loaderContext.callback(null,style.content,style.map)return}// customif (query.type === 'custom' && query.index != null) {const block = descriptor.customBlocks[query.index]loaderContext.callback(null,block.content,block.map)return} }最后經(jīng)過(guò)select輸出:
<div class="app-container">{{ msg }}</div>ok,然后vue-loader處理完后給到了“…/node_modules/vue-loader/lib/loaders/templateLoader.js”,
/node_modules/vue-loader/lib/loaders/templateLoader.js:
const qs = require('querystring') const loaderUtils = require('loader-utils') const { compileTemplate } = require('@vue/component-compiler-utils')// Loader that compiles raw template into JavaScript functions. // This is injected by the global pitcher (../pitch) for template // selection requests initiated from vue files. module.exports = function (source) {const loaderContext = thisconst query = qs.parse(this.resourceQuery.slice(1))// although this is not the main vue-loader, we can get access to the same// vue-loader options because we've set an ident in the plugin and used that// ident to create the request for this loader in the pitcher.const options = loaderUtils.getOptions(loaderContext) || {}const { id } = queryconst isServer = loaderContext.target === 'node'const isProduction = options.productionMode || loaderContext.minimize || process.env.NODE_ENV === 'production'const isFunctional = query.functional// allow using custom compiler via optionsconst compiler = options.compiler || require('vue-template-compiler')const compilerOptions = Object.assign({outputSourceRange: true}, options.compilerOptions, {scopeId: query.scoped ? `data-v-${id}` : null,comments: query.comments})// for vue-component-compilerconst finalOptions = {source,filename: this.resourcePath,compiler,compilerOptions,// allow customizing behavior of vue-template-es2015-compilertranspileOptions: options.transpileOptions,transformAssetUrls: options.transformAssetUrls || true,isProduction,isFunctional,optimizeSSR: isServer && options.optimizeSSR !== false,prettify: options.prettify}const compiled = compileTemplate(finalOptions)// tipsif (compiled.tips && compiled.tips.length) {compiled.tips.forEach(tip => {loaderContext.emitWarning(typeof tip === 'object' ? tip.msg : tip)})}// errorsif (compiled.errors && compiled.errors.length) {// 2.6 compiler outputs errors as objects with rangeif (compiler.generateCodeFrame && finalOptions.compilerOptions.outputSourceRange) {// TODO account for line offset in case template isn't placed at top// of the fileloaderContext.emitError(`\n\n Errors compiling template:\n\n` +compiled.errors.map(({ msg, start, end }) => {const frame = compiler.generateCodeFrame(source, start, end)return ` ${msg}\n\n${pad(frame)}`}).join(`\n\n`) +'\n')} else {loaderContext.emitError(`\n Error compiling template:\n${pad(compiled.source)}\n` +compiled.errors.map(e => ` - ${e}`).join('\n') +'\n')}}const { code } = compiled// finish with ESM exportsreturn code + `\nexport { render, staticRenderFns }` }function pad (source) {return source.split(/\r?\n/).map(line => ` ${line}`).join('\n') }我們看一下“/node_modules/vue-loader/lib/loaders/templateLoader.js”處理完后又變成什么樣了?
var render = function() {var _vm = thisvar _h = _vm.$createElementvar _c = _vm._self._c || _hreturn _c("div", { staticClass: "app-container" }, [_vm._v(_vm._s(_vm.msg))]) } var staticRenderFns = [] render._withStripped = true export { render, staticRenderFns}總結(jié)
ok,終于是轉(zhuǎn)完畢了,我們?cè)購(gòu)男禄仡櫼幌抡麄€(gè)流程(我這里以app.vue的template為例子)。
首先是我們的app.vue文件template:
<template><div class="app-container">{{ msg }}</div> </template>然后經(jīng)過(guò)vue-loader后:
import { render, staticRenderFns } from "./app.vue?vue&type=template&id=5ef48958&scoped=true&"然后是pitcher-loader:
export * from "-!../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../node_modules/vue-loader/lib/index.js??vue-loader-options!./app.vue?vue&type=template&id=5ef48958&scoped=true&"接著又是vue-loader:
<div class="app-container">{{ msg }}</div>然后是…/node_modules/vue-loader/lib/loaders/templateLoader.js:
var render = function() {var _vm = thisvar _h = _vm.$createElementvar _c = _vm._self._c || _hreturn _c("div", { staticClass: "app-container" }, [_vm._v(_vm._s(_vm.msg))]) } var staticRenderFns = [] render._withStripped = true export { render, staticRenderFns }ok, app.vue中的template模塊解析過(guò)程就是這樣的了,還有script跟style,過(guò)程都差不多,小伙伴自己結(jié)合demo跟斷點(diǎn)跑一下哦,我就不演示了!
補(bǔ)充
vue模塊熱載
webpack中的模塊熱載集成大家可以看webpack官網(wǎng):https://webpack.js.org/api/hot-module-replacement/.
當(dāng)我們的app.vue第一次經(jīng)過(guò)vue-loader后:
import { render, staticRenderFns } from "./app.vue?vue&type=template&id=5ef48958&scoped=true&" import script from "./app.vue?vue&type=script&lang=ts&" export * from "./app.vue?vue&type=script&lang=ts&" import style0 from "./app.vue?vue&type=style&index=0&id=5ef48958&scoped=true&lang=scss&"/* normalize component */ import normalizer from "!../node_modules/vue-loader/lib/runtime/componentNormalizer.js" var component = normalizer(script,render,staticRenderFns,false,null,"5ef48958",null)/* hot reload */ if (module.hot) {//加載vue模塊熱載代碼var api = require("xxx/node_modules/vue-hot-reload-api/dist/index.js")api.install(require('vue'))if (api.compatible) {module.hot.accept() //把當(dāng)前模塊加入到webpack的熱載中(當(dāng)前模塊有變換的時(shí)候會(huì)通知)if (!api.isRecorded('5ef48958')) { //第一次的時(shí)候記錄當(dāng)前組件api.createRecord('5ef48958', component.options)} else { //熱載的時(shí)候從新渲染當(dāng)前組件api.reload('5ef48958', component.options)}//模塊代碼改變的時(shí)候也認(rèn)為可以熱載,通知當(dāng)前組件刷新module.hot.accept("./app.vue?vue&type=template&id=5ef48958&scoped=true&", function () {api.rerender('5ef48958', {render: render,staticRenderFns: staticRenderFns})})} } component.options.__file = "src/app.vue" export default component.exportsnode_modules/vue-hot-reload-api/dist/index.js:
exports.reload = tryWrap(function (id, options) {...record.instances.slice().forEach(function (instance) {if (instance.$vnode && instance.$vnode.context) {instance.$vnode.context.$forceUpdate() //強(qiáng)制刷新組件} else {console.warn('Root or manually mounted instance modified. Full reload required.')}}) })ok!整個(gè)vue-loader流程我們差不多擼了一遍,其實(shí)掌握了webpack后這東西感覺(jué)也不是很難了對(duì)吧?😄😄,所以強(qiáng)烈推薦小伙伴看看之前的webpack的文章,覺(jué)得不錯(cuò)的也可以關(guān)注跟點(diǎn)點(diǎn)贊哦! 也歡迎志同道合的小伙伴一起學(xué)習(xí)一起交流!!
總結(jié)
以上是生活随笔為你收集整理的手把手带你撸一遍vue-loader源码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Ylmf OS 4.0最新公开测试版发布
- 下一篇: Kali安装VMware Tools,解