├── .eslintrc ├── .gitignore ├── .nvmrc ├── LICENSE ├── README.md ├── jest.config.js ├── lib ├── generate-component-imports.js ├── get-unregistered-components.js ├── index.js ├── resolve-components.js └── utils.js ├── package-lock.json ├── package.json └── test ├── .eslintrc ├── index.spec.js └── utils.js /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb-base", 3 | "env": { 4 | "node": true, 5 | "browser": false 6 | }, 7 | "rules": { 8 | "indent": "off", 9 | "indent-legacy": ["error", "tab"], 10 | "no-tabs": "off" 11 | } 12 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | 3 | # Logs 4 | logs 5 | *.log 6 | npm-debug.log* 7 | yarn-debug.log* 8 | yarn-error.log* 9 | lerna-debug.log* 10 | 11 | # Diagnostic reports (https://nodejs.org/api/report.html) 12 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 13 | 14 | # Runtime data 15 | pids 16 | *.pid 17 | *.seed 18 | *.pid.lock 19 | 20 | # Directory for instrumented libs generated by jscoverage/JSCover 21 | lib-cov 22 | 23 | # Coverage directory used by tools like istanbul 24 | coverage 25 | *.lcov 26 | 27 | # nyc test coverage 28 | .nyc_output 29 | 30 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 31 | .grunt 32 | 33 | # Bower dependency directory (https://bower.io/) 34 | bower_components 35 | 36 | # node-waf configuration 37 | .lock-wscript 38 | 39 | # Compiled binary addons (https://nodejs.org/api/addons.html) 40 | build/Release 41 | 42 | # Dependency directories 43 | node_modules/ 44 | jspm_packages/ 45 | 46 | # TypeScript v1 declaration files 47 | typings/ 48 | 49 | # TypeScript cache 50 | *.tsbuildinfo 51 | 52 | # Optional npm cache directory 53 | .npm 54 | 55 | # Optional eslint cache 56 | .eslintcache 57 | 58 | # Microbundle cache 59 | .rpt2_cache/ 60 | .rts2_cache_cjs/ 61 | .rts2_cache_es/ 62 | .rts2_cache_umd/ 63 | 64 | # Optional REPL history 65 | .node_repl_history 66 | 67 | # Output of 'npm pack' 68 | *.tgz 69 | 70 | # Yarn Integrity file 71 | .yarn-integrity 72 | 73 | # dotenv environment variables file 74 | .env 75 | .env.test 76 | 77 | # parcel-bundler cache (https://parceljs.org/) 78 | .cache 79 | 80 | # Next.js build output 81 | .next 82 | 83 | # Nuxt.js build / generate output 84 | .nuxt 85 | dist 86 | 87 | # Gatsby files 88 | .cache/ 89 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 90 | # https://nextjs.org/blog/next-9-1#public-directory-support 91 | # public 92 | 93 | # vuepress build output 94 | .vuepress/dist 95 | 96 | # Serverless directories 97 | .serverless/ 98 | 99 | # FuseBox cache 100 | .fusebox/ 101 | 102 | # DynamoDB Local files 103 | .dynamodb/ 104 | 105 | # TernJS port file 106 | .tern-port 107 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | v12.16.2 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Hiroki Osame 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🌐 Vue Import Loader 2 | 3 | Webpack loader to automate local component registration by statically analyzing components in the template. 4 | 5 | Credits to the [@nuxt/components](https://github.com/nuxt/components) for the idea ❤️ 6 | 7 | ## ⭐️ Features 8 | - 🌳 **Tree-shaking** Only imports unregistered components detected in the template 9 | - ❤️ **Chunking friendly** Locally registers components for optimal code-splitting 10 | - ⚡️ **Async components** Supports the full [async component API](https://vuejs.org/v2/guide/components-dynamic-async.html#Async-Components) 11 | - 💠 **Dynamic components** Supports `` * 12 | - 🔥 **Functional components** Supports components in [functional components](https://github.com/vuejs/vue-loader/issues/1013) 13 | 14 | _* The `is` attribute must contain the possible values inline_ 15 | 16 | ## :rocket: Install 17 | ```sh 18 | npm i vue-import-loader 19 | ``` 20 | 21 | ## 🚦 Quick Setup 22 | In your Webpack config, insert `vue-import-loader` before `vue-loader`: 23 | 24 | **Before** 25 | ```diff 26 | { 27 | test: /\.vue$/, 28 | - loader: 'vue-loader' 29 | } 30 | ``` 31 | 32 | **After ** 33 | ```diff 34 | { 35 | test: /\.vue$/, 36 | + use: [ 37 | + { 38 | + loader: 'vue-import-loader', 39 | + options: { 40 | + 41 | + // Similar to Vue's "components" hash 42 | + components: { 43 | + ComponentTag: 'component/path/component-tag.vue', 44 | + ... 45 | + } 46 | + } 47 | + }, 48 | + 'vue-loader' 49 | + ] 50 | } 51 | ``` 52 | 53 | ## 👨‍🏫 Examples 54 | 55 |
56 | Dynamically resolve components to a directory 57 |
58 | 59 | Use a resolver function to dynamically resolve components 60 | 61 | ```js 62 | { 63 | test: /\.vue$/, 64 | use: [ 65 | { 66 | loader: 'vue-import-loader', 67 | options: { 68 | components({ kebab }, fromComponent) { 69 | if (exists(kebab)) { 70 | return `@/components/${kebab}`; 71 | } 72 | } 73 | } 74 | }, 75 | 'vue-loader' 76 | ] 77 | } 78 | ``` 79 |
80 | 81 |
82 | Asynchronously load components with `components` hash 83 |
84 | 85 | Map the component to an object to make it asynchronous. Refer to the **Options** section for the object schema. 86 | 87 | ```js 88 | { 89 | test: /\.vue$/, 90 | use: [ 91 | { 92 | loader: 'vue-import-loader', 93 | options: { 94 | components: { 95 | SyncComp: '/components/sync-comp.vue', 96 | 97 | // Mapping to an object makes it asynchronous 98 | AsyncComp: { 99 | component: '/components/async-comp.vue', 100 | 101 | // Optional configs 102 | loading: '/components/loading.vue', 103 | error: '/components/error.vue', 104 | magicComments: ['webpackChunkName: "async-comps"'] 105 | } 106 | } 107 | } 108 | }, 109 | 'vue-loader' 110 | ] 111 | } 112 | ``` 113 |
114 | 115 |
116 | Asynchronously load components prefixed with `async-` 117 |
118 | 119 | Return an object to make it asynchronous. Refer to the **Options** section for the object schema. 120 | 121 | This demo shows how prefixing your components with `async-` in the template can make them asynchronously loaded. 122 | 123 | ```js 124 | { 125 | test: /\.vue$/, 126 | use: [ 127 | { 128 | loader: 'vue-import-loader', 129 | options: { 130 | components({ kebab }) { 131 | if (kebab.startsWith('async-')) { 132 | return { 133 | component: `/components/${kebab.replace(/^async-/)}.vue`, 134 | 135 | // Optional configs 136 | loading: '/components/loading.vue', 137 | error: '/components/error.vue', 138 | magicComments: ['webpackChunkName: "async-comps"'] 139 | }; 140 | } 141 | 142 | return `/components/${kebab}.vue`; 143 | } 144 | } 145 | }, 146 | 'vue-loader' 147 | ] 148 | } 149 | ``` 150 |
151 | 152 | 153 | ## ⚙️ Options 154 | - `components` `Object|Function` 155 | - `Object` Similar to Vue's `components` hash. Key is the component tag in kebab-case or PascalCase. 156 | - Value can be: 157 | - `String`: Component path for synchronous loading (supports aliases) 158 | - `Object`: Component data for [asynchronous loading](https://vuejs.org/v2/guide/components-dynamic-async.html#Async-Components) meeting the following schema: 159 | 160 | 161 | ```js 162 | { 163 | // Component path (Required) 164 | component: '...', 165 | 166 | // Loading component path 167 | loading: '...', 168 | 169 | // Error component path 170 | error: '...', 171 | 172 | // Delay in ms before Loading component is displayed 173 | delay: 200, 174 | 175 | // Timeout in ms before Error component is displayed 176 | timeout: Infinity, 177 | 178 | // Magic comments to configure the dynamic import: 179 | // https://webpack.js.org/api/module-methods/#magic-comments 180 | magicComponents: [ 181 | 'webpackChunkName: "my-chunk-name"' 182 | ] 183 | } 184 | ``` 185 | 186 | - `Function` `({ kebab, pascal }, fromComponent)` 187 | - Use a function to dynamically resolve component tags to component paths. Supports outputting a string for synchronous, and an object for asynchronous imports as defined above. For example, this function resolves components to the "components" directory: 188 | ```js 189 | components({ kebab }, fromComponent) { 190 | const componentPath = `../components/${kebab}.vue`; 191 | if (fs.existsSync(componentPath)) { 192 | return `@/components/${kebab}`; 193 | } 194 | } 195 | ``` 196 | 197 | - `functional` (_Experimental_) `Boolean` (Default: `false`) 198 | - Whether to resolve components in functional components. Functional components are [known to not support the `components` hash](https://github.com/vuejs/vue-loader/issues/1013) but can be hacked around by registering the components to the parent instead. Since this feature mutates the parent's `component` hash, it is disabled by default. 199 | 200 | ## 💁‍♂️ FAQ 201 | ### How's this different from Vue's [global registration](https://vuejs.org/v2/guide/components-registration.html#Global-Registration)? 202 | - **Global registration** 203 | - Bundles-in registered components regardless of whether they're actually used 204 | - Registers components to the Vue runtime, making them available to all-components 205 | - Could lead to component name collision in large code-bases 206 | 207 | - **Vue Import loader** 208 | - Only bundles-in components that it detects in the app's Vue component templates 209 | - Components are registered locally per-component for optimal code-splitting 210 | - Nuanced control over which files get what components via resolution function 211 | 212 | ### How's this different from [Nuxt.js Components](https://github.com/nuxt/components)? 213 | - **Nuxt.js Components** 214 | - Designed specifically for [Nuxt.js](https://nuxtjs.org) 215 | - Automatically resolves components in the "components" directory 216 | - Supports async components but not the full API (eg. `loading`, `error`, `delay`, `timeout`) 217 | 218 | - **Vue Import loader** 219 | - Supports any Webpack build 220 | - Resolves components using a user-configured component-map or a resolution function 221 | - Has built-in static analysis to detect registered components 222 | - Supports the full [async component API](https://vuejs.org/v2/guide/components-dynamic-async.html#Async-Components) 223 | - Supports dynamic components if possible values are inline 224 | - eg. `` 225 | - Supports [functional components](https://github.com/vuejs/vue-loader/issues/1013) 226 | 227 | ### Why wouldn't I want to use this? 228 | The costs of implicitly registering components locally is close to [registering components globally](https://vuejs.org/v2/guide/components-registration.html#Global-Registration). 229 | 230 | - The benefit this has over global registration is that it doesn't import components blindly at the top-level of your App, but instead, imports them intelligently at each detected usage. Unused components will not be bundled-in. 231 | 232 | - **Maintainability** Your components might become harder to maintain because of the lack of explicitly declared dependencies. 233 | - **Automation magic** It's better to have code you understand and can control than to leave it to _magic_. 234 | - **Debugging** If there's a bug in your resolver, it might not be an obvious place to look or troubleshoot. 235 | 236 | - **Build-tool coupling** Module-level concerns are introduced into the build configuration; perhaps comparable to creating aliases. Doing this couples the app to the build via config and makes it harder to migrate to a different environment (new tools, upgrades, etc). 237 | 238 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | testEnvironmentOptions: { 3 | resources: 'usable', 4 | }, 5 | }; 6 | -------------------------------------------------------------------------------- /lib/generate-component-imports.js: -------------------------------------------------------------------------------- 1 | function asyncImport(asyncObj, compName) { 2 | if ( 3 | typeof asyncObj !== 'object' 4 | || typeof asyncObj.component !== 'string' 5 | ) { 6 | return null; 7 | } 8 | 9 | const magicComments = Array.isArray(asyncObj.magicComments) 10 | ? asyncObj.magicComments.map((c) => `/* ${c} */`).join(' ') : ''; 11 | 12 | const importStatements = []; 13 | const asyncHash = [`component: import(${magicComments}${JSON.stringify(asyncObj.component)})`]; 14 | 15 | if (asyncObj.loading) { 16 | const name = `${compName}Loading`; 17 | importStatements.push(`import ${name} from '${asyncObj.loading}';`); 18 | asyncHash.push(`loading:${name}`); 19 | } 20 | 21 | if (asyncObj.error) { 22 | const name = `${compName}Error`; 23 | importStatements.push(`import ${name} from '${asyncObj.error}';`); 24 | asyncHash.push(`error:${name}`); 25 | } 26 | 27 | if (typeof asyncObj.delay === 'number') { 28 | asyncHash.push(`delay:${asyncObj.delay}`); 29 | } 30 | 31 | if (typeof asyncObj.timeout === 'number') { 32 | asyncHash.push(`timeout:${asyncObj.timeout}`); 33 | } 34 | 35 | return { 36 | importStatements, 37 | component: `() => ({${asyncHash.join(',')}})`, 38 | }; 39 | } 40 | 41 | function generateComponentImports(resolvedComponents) { 42 | const componentsHash = []; 43 | const importStatements = []; 44 | 45 | resolvedComponents.forEach(([name, specifier], idx) => { 46 | const compName = `c${idx}`; 47 | const isAsync = asyncImport(specifier, compName); 48 | 49 | if (isAsync) { 50 | importStatements.push(...isAsync.importStatements); 51 | componentsHash.push(`${name}: ${isAsync.component}`); 52 | } else if (typeof specifier === 'string') { 53 | importStatements.push(`import ${compName} from '${specifier}';`); 54 | componentsHash.push(`${name}:${compName}`); 55 | } 56 | }); 57 | 58 | return { 59 | componentsHash: componentsHash.join(','), 60 | importStatements: importStatements.join(''), 61 | }; 62 | } 63 | 64 | module.exports = generateComponentImports; 65 | -------------------------------------------------------------------------------- /lib/get-unregistered-components.js: -------------------------------------------------------------------------------- 1 | const { Parser } = require('acorn'); 2 | const jsx = require('acorn-jsx'); 3 | const walk = require('acorn-walk'); 4 | const { compile, parseComponent } = require('vue-template-compiler'); 5 | const { pascalize, pluck } = require('./utils'); 6 | 7 | const acorn = Parser.extend(jsx()); 8 | 9 | // fix: https://github.com/acornjs/acorn/issues/829 10 | Object.assign(walk.base, { JSXElement: () => {} }); 11 | 12 | function detectTplTags(tplContent) { 13 | const tags = new Set(); 14 | 15 | compile(tplContent, { 16 | modules: [{ 17 | postTransformNode({ tag, component }) { 18 | if (tag === 'component') { 19 | walk.simple(acorn.parse(component), { 20 | Literal({ value }) { 21 | if (typeof value === 'string') { 22 | tags.add(pascalize(value)); 23 | } 24 | }, 25 | }); 26 | } else { 27 | tags.add(pascalize(tag)); 28 | } 29 | }, 30 | }], 31 | }); 32 | return Array.from(tags); 33 | } 34 | 35 | function findComponentHash(compNode) { 36 | if (compNode.type === 'ObjectExpression' && compNode.properties) { 37 | const componentHash = compNode.properties.find((p) => p.key.name === 'components'); 38 | if (componentHash) { 39 | return componentHash.value; 40 | } 41 | } 42 | return null; 43 | } 44 | 45 | function getLocallyRegisteredComponents(scriptContent) { 46 | const components = new Set(); 47 | walk.simple(acorn.parse(scriptContent, { sourceType: 'module' }), { 48 | ExportDefaultDeclaration({ declaration }) { 49 | const componentHash = findComponentHash(declaration); 50 | 51 | if (!componentHash) { return; } 52 | 53 | componentHash.properties.forEach((property) => { 54 | if (property.type === 'Property') { 55 | if ( 56 | property.computed 57 | && property.key.type === 'Literal' 58 | && typeof property.key.value === 'string' 59 | ) { 60 | components.add(pascalize(property.key.value)); 61 | } 62 | 63 | if ( 64 | !property.computed 65 | && property.key.type === 'Identifier' 66 | ) { 67 | components.add(pascalize(property.key.name)); 68 | } 69 | } 70 | }); 71 | }, 72 | }); 73 | return components; 74 | } 75 | 76 | function getUnregisteredComponents(src) { 77 | const component = parseComponent(src); 78 | 79 | if (!component.template) { return []; } 80 | 81 | const unregisteredComponents = detectTplTags(component.template.content); 82 | 83 | if (component.script) { 84 | // eslint-disable-next-line no-restricted-syntax 85 | for (const comp of getLocallyRegisteredComponents(component.script.content)) { 86 | pluck(unregisteredComponents, comp); 87 | } 88 | } 89 | 90 | return unregisteredComponents; 91 | } 92 | 93 | module.exports = getUnregisteredComponents; 94 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | const loaderUtils = require('loader-utils'); 2 | const outdent = require('outdent'); 3 | const getUnregisteredComponents = require('./get-unregistered-components'); 4 | const resolveComponents = require('./resolve-components'); 5 | const generateComponentImports = require('./generate-component-imports'); 6 | 7 | const exportDefault = 'export default'; 8 | function injectPayload(src, payload) { 9 | const foundExport = src.indexOf(exportDefault); 10 | return (foundExport > -1) ? `${src.slice(0, foundExport) + payload}\n\n${src.slice(foundExport)}` : src; 11 | } 12 | 13 | const defaultOpts = { 14 | components: undefined, 15 | functional: false, 16 | }; 17 | 18 | function vueImportLoader(src) { 19 | const params = loaderUtils.parseQuery(this.resourceQuery || '?'); 20 | const options = { ...defaultOpts, ...loaderUtils.getOptions(this) }; 21 | 22 | if ( 23 | params.vue 24 | || !(options.components && ['object', 'function'].includes(typeof options.components)) 25 | ) { 26 | return src; 27 | } 28 | 29 | const unregistered = getUnregisteredComponents( 30 | this.fs.readFileSync(this.resourcePath).toString(), 31 | ); 32 | 33 | const { componentsHash, importStatements } = generateComponentImports(resolveComponents( 34 | this.resourcePath, 35 | unregistered, 36 | options.components, 37 | )); 38 | 39 | if (componentsHash.length) { 40 | return injectPayload(src, outdent` 41 | 42 | /* vue-import-loader */ 43 | ${importStatements} 44 | var __components = {${componentsHash}}; 45 | 46 | if (${options.functional} && component.exports.functional) { 47 | var __origRender = component.exports.render; 48 | component.exports.render = function(_, ctx) { 49 | ctx.parent.$options.components = Object.assign({}, __components, ctx.parent.$options.components); 50 | return __origRender.apply(this, arguments); 51 | }; 52 | } else { 53 | component.exports.components = Object.assign({}, __components, component.exports.components); 54 | } 55 | `); 56 | } 57 | 58 | return src; 59 | } 60 | 61 | module.exports = vueImportLoader; 62 | -------------------------------------------------------------------------------- /lib/resolve-components.js: -------------------------------------------------------------------------------- 1 | const { hasOwn, hyphenate } = require('./utils'); 2 | 3 | function resolveComponents(resourcePath, unresolved, components) { 4 | const importMap = {}; 5 | 6 | unresolved.forEach((tag) => { 7 | if (importMap[tag]) { return; } 8 | 9 | const kebab = hyphenate(tag); 10 | 11 | let resolved; 12 | 13 | if (typeof components === 'function') { 14 | resolved = components({ pascal: tag, kebab }, resourcePath); 15 | } else if (hasOwn(components, kebab)) { 16 | resolved = components[kebab]; 17 | } else if (hasOwn(components, tag)) { 18 | resolved = components[tag]; 19 | } 20 | 21 | if (resolved) { 22 | importMap[tag] = resolved; 23 | } 24 | }); 25 | 26 | return Object.entries(importMap); 27 | } 28 | 29 | 30 | module.exports = resolveComponents; 31 | -------------------------------------------------------------------------------- /lib/utils.js: -------------------------------------------------------------------------------- 1 | // Source: https://github.com/vuejs/vue/blob/dev/src/shared/util.js 2 | const hyphenateRE = /\B([A-Z])/g; 3 | const hyphenate = (pascal) => pascal.replace(hyphenateRE, '-$1').toLowerCase(); 4 | 5 | const capitalize = (str) => str[0].toUpperCase() + str.slice(1); 6 | 7 | const camelizeRE = /-(\w)/g; 8 | const pascalize = (kebab) => capitalize(kebab.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))); 9 | 10 | const { hasOwnProperty } = Object.prototype; 11 | const hasOwn = (obj, prop) => hasOwnProperty.call(obj, prop); 12 | 13 | const pluck = (arr, el) => { 14 | const idx = arr.indexOf(el); 15 | if (idx > -1) { 16 | arr.splice(idx, 1); 17 | } 18 | }; 19 | 20 | module.exports = { 21 | pascalize, 22 | hyphenate, 23 | hasOwn, 24 | pluck, 25 | }; 26 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vue-import-loader", 3 | "version": "0.0.1", 4 | "description": "Webpack loader to automatically detect & import used components", 5 | "keywords": [ 6 | "webpack", 7 | "vue", 8 | "loader", 9 | "components", 10 | "import" 11 | ], 12 | "files": [ 13 | "lib" 14 | ], 15 | "main": "lib/index.js", 16 | "scripts": { 17 | "lint": "eslint .", 18 | "test": "jest" 19 | }, 20 | "husky": { 21 | "hooks": { 22 | "pre-commit": "lint-staged" 23 | } 24 | }, 25 | "lint-staged": { 26 | "*.js": [ 27 | "eslint --fix", 28 | "jest --bail --findRelatedTests" 29 | ] 30 | }, 31 | "repository": { 32 | "type": "git", 33 | "url": "git+https://github.com/privatenumber/vue-import-loader.git" 34 | }, 35 | "author": "Hiroki Osame ", 36 | "license": "MIT", 37 | "bugs": { 38 | "url": "https://github.com/privatenumber/vue-import-loader/issues" 39 | }, 40 | "homepage": "https://github.com/privatenumber/vue-import-loader#readme", 41 | "devDependencies": { 42 | "eslint": "^6.8.0", 43 | "eslint-config-airbnb-base": "^14.1.0", 44 | "eslint-plugin-import": "^2.20.2", 45 | "husky": "^4.2.5", 46 | "jest": "^26.0.1", 47 | "lint-staged": "^10.2.6", 48 | "memfs": "^3.2.0", 49 | "unionfs": "^4.4.0", 50 | "vue": "^2.6.11", 51 | "vue-loader": "^15.9.2", 52 | "webpack": "^4.43.0" 53 | }, 54 | "dependencies": { 55 | "acorn": "^7.2.0", 56 | "acorn-jsx": "^5.2.0", 57 | "acorn-walk": "^7.1.1", 58 | "loader-utils": "^2.0.0", 59 | "outdent": "^0.7.1", 60 | "vue-template-compiler": "^2.6.11" 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /test/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "jest": true, 4 | "browser": true 5 | } 6 | } -------------------------------------------------------------------------------- /test/index.spec.js: -------------------------------------------------------------------------------- 1 | const outdent = require('outdent'); 2 | const Vue = require('vue'); 3 | const { httpServer, build, mount } = require('./utils'); 4 | 5 | const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); 6 | 7 | Vue.config.productionTip = false; 8 | Vue.config.devtools = false; 9 | 10 | beforeAll(() => httpServer.start()); 11 | afterAll(() => httpServer.stop()); 12 | afterEach(() => { 13 | window.webpackJsonp = null; 14 | }); 15 | 16 | describe('Error handling', () => { 17 | test('No options', async () => { 18 | const built = await build({ 19 | '/index.vue': outdent` 20 | 23 | `, 24 | '/CustomComp.vue': outdent` 25 | 28 | `, 29 | }); 30 | 31 | const warnHandler = jest.fn(); 32 | Vue.config.warnHandler = warnHandler; 33 | 34 | const vm = mount(Vue, built); 35 | 36 | expect(warnHandler).toBeCalled(); 37 | expect(vm.$el.outerHTML).toBe('

Hello

'); 38 | }); 39 | 40 | test('No options.components', async () => { 41 | const built = await build({ 42 | '/index.vue': outdent` 43 | 46 | `, 47 | '/CustomComp.vue': outdent` 48 | 51 | `, 52 | }, {}); 53 | 54 | const warnHandler = jest.fn(); 55 | Vue.config.warnHandler = warnHandler; 56 | 57 | const vm = mount(Vue, built); 58 | 59 | expect(warnHandler).toBeCalled(); 60 | expect(vm.$el.outerHTML).toBe('

Hello

'); 61 | }); 62 | }); 63 | 64 | describe('Component Registration', () => { 65 | test('Single component', async () => { 66 | const built = await build({ 67 | '/index.vue': outdent` 68 | 71 | `, 72 | '/CustomComp.vue': outdent` 73 | 76 | `, 77 | }, { 78 | components: { 79 | CustomComp: '/CustomComp.vue', 80 | }, 81 | }); 82 | 83 | const vm = mount(Vue, built); 84 | 85 | expect(vm.$el.outerHTML).toBe('

Hello world

'); 86 | }); 87 | 88 | test('Multiple components', async () => { 89 | const built = await build({ 90 | '/index.vue': outdent` 91 | 97 | `, 98 | '/world.vue': outdent` 99 | 102 | `, 103 | '/goodbyeWorld.vue': outdent` 104 | 107 | `, 108 | }, { 109 | components: { 110 | world: '/world.vue', 111 | 'goodbye-world': '/goodbyeWorld.vue', 112 | UnusedComp: '/should-not-exist.vue', 113 | }, 114 | }); 115 | 116 | const vm = mount(Vue, built); 117 | expect(vm.$el.outerHTML).toBe('

Hello world

goodbye world

'); 118 | }); 119 | 120 | test('Multiple files', async () => { 121 | const built = await build({ 122 | '/index.vue': outdent` 123 | 129 | `, 130 | '/world.vue': outdent` 131 | 134 | `, 135 | '/goodbyeWorld.vue': outdent` 136 | 139 | `, 140 | }, { 141 | components: { 142 | 'world-el': '/world.vue', 143 | 'goodbye-world': '/goodbyeWorld.vue', 144 | UnusedComp: '/should-not-exist.vue', 145 | }, 146 | }); 147 | 148 | const vm = mount(Vue, built); 149 | expect(vm.$el.outerHTML).toBe('

Hello world

goodbye world

'); 150 | }); 151 | 152 | test('Component collision w/ Pascal', async () => { 153 | const built = await build({ 154 | '/index.vue': outdent` 155 | 160 | 169 | `, 170 | '/hello-world-real.vue': outdent` 171 | 174 | `, 175 | '/hello-world-fake.vue': outdent` 176 | 179 | `, 180 | }, { 181 | components: { 182 | 'hello-world': '/hello-world-fake.vue', 183 | }, 184 | }); 185 | 186 | const vm = mount(Vue, built); 187 | expect(vm.$el.outerHTML).toBe('
hello world real
'); 188 | }); 189 | 190 | test('Component collision w/ kebab', async () => { 191 | const built = await build({ 192 | '/index.vue': outdent` 193 | 198 | 207 | `, 208 | '/hello-world-real.vue': outdent` 209 | 212 | `, 213 | '/hello-world-fake.vue': outdent` 214 | 217 | `, 218 | }, { 219 | components: { 220 | 'hello-world': '/hello-world-fake.vue', 221 | }, 222 | }); 223 | 224 | const vm = mount(Vue, built); 225 | expect(vm.$el.outerHTML).toBe('
hello world real
'); 226 | }); 227 | 228 | test('Dynamic component', async () => { 229 | const built = await build({ 230 | '/index.vue': outdent` 231 | 237 | `, 238 | '/world.vue': outdent` 239 | 242 | `, 243 | '/goodbyeWorld.vue': outdent` 244 | 247 | `, 248 | }, { 249 | components: { 250 | world: '/world.vue', 251 | 'goodbye-world': '/goodbyeWorld.vue', 252 | UnusedComp: '/should-not-exist.vue', 253 | }, 254 | }); 255 | 256 | const vm = mount(Vue, built); 257 | expect(vm.$el.outerHTML).toBe('
world

goodbye world

'); 258 | }); 259 | 260 | test('Alias', async () => { 261 | const built = await build({ 262 | '/index.vue': outdent` 263 | 269 | `, 270 | '/components/world.vue': outdent` 271 | 274 | `, 275 | '/components/goodbyeWorld.vue': outdent` 276 | 279 | `, 280 | }, { 281 | components: { 282 | world: '@/components/world.vue', 283 | 'goodbye-world': '@/components/goodbyeWorld.vue', 284 | UnusedComp: '@/components/should-not-exist.vue', 285 | }, 286 | }); 287 | 288 | const vm = mount(Vue, built); 289 | expect(vm.$el.outerHTML).toBe('

Hello world

goodbye world

'); 290 | }); 291 | 292 | test('Resolve function', async () => { 293 | const built = await build({ 294 | '/index.vue': outdent` 295 | 301 | `, 302 | '/components/world.vue': outdent` 303 | 306 | `, 307 | '/components/goodbye-world.vue': outdent` 308 | 311 | `, 312 | }, { 313 | components({ kebab }) { 314 | if (['world', 'goodbye-world'].includes(kebab)) { 315 | return `/components/${kebab}.vue`; 316 | } 317 | return undefined; 318 | }, 319 | }); 320 | 321 | const vm = mount(Vue, built); 322 | expect(vm.$el.outerHTML).toBe('

Hello world

goodbye world

'); 323 | }); 324 | }); 325 | 326 | 327 | describe('Async components', () => { 328 | test('Basic async component', async () => { 329 | const built = await build({ 330 | '/index.vue': outdent` 331 | 336 | `, 337 | '/HelloWorld.vue': outdent` 338 | 341 | `, 342 | '/LoadingComponent.vue': outdent` 343 | 346 | `, 347 | '/ErrorComponent.vue': outdent` 348 | 351 | `, 352 | }, { 353 | components: { 354 | HelloWorld: { 355 | component: '/HelloWorld.vue', 356 | loading: '/LoadingComponent.vue', 357 | error: '/ErrorComponent.vue', 358 | delay: 0, 359 | timeout: 3000, 360 | }, 361 | }, 362 | }); 363 | 364 | const vm = mount(Vue, built); 365 | 366 | expect(vm.$el.outerHTML).toBe('

Loading

'); 367 | 368 | await sleep(300); 369 | expect(vm.$el.outerHTML).toBe('
Hello world
'); 370 | }, 2000); 371 | 372 | test('Magic comments', async () => { 373 | const built = await build({ 374 | '/index.vue': outdent` 375 | 380 | `, 381 | '/HelloWorlds.vue': outdent` 382 | 385 | `, 386 | '/LoadingComponent.vue': outdent` 387 | 390 | `, 391 | '/ErrorComponent.vue': outdent` 392 | 395 | `, 396 | }, { 397 | components: { 398 | HelloWorld: { 399 | magicComments: [ 400 | 'webpackChunkName: "my-chunk-name"', 401 | 'webpackPrefetch: true', 402 | 'webpackPreload: true', 403 | ], 404 | component: '/HelloWorlds.vue', 405 | loading: '/LoadingComponent.vue', 406 | error: '/ErrorComponent.vue', 407 | }, 408 | }, 409 | }); 410 | 411 | expect(built).toMatch('my-chunk-name'); 412 | 413 | const vm = mount(Vue, built); 414 | 415 | expect(vm.$el.outerHTML).toBe('
'); 416 | 417 | await sleep(200); 418 | expect(vm.$el.outerHTML).toBe('

Loading

'); 419 | 420 | await sleep(200); 421 | expect(vm.$el.outerHTML).toBe('
Hello worlds!!!!!!
'); 422 | }, 2000); 423 | 424 | test('Magic comments - eager', async () => { 425 | const built = await build({ 426 | '/index.vue': outdent` 427 | 432 | `, 433 | '/HelloWorlds.vue': outdent` 434 | 437 | `, 438 | '/LoadingComponent.vue': outdent` 439 | 442 | `, 443 | '/ErrorComponent.vue': outdent` 444 | 447 | `, 448 | }, { 449 | components: { 450 | HelloWorld: { 451 | magicComments: ['webpackMode: "eager"'], 452 | component: '/HelloWorlds.vue', 453 | loading: '/LoadingComponent.vue', 454 | error: '/ErrorComponent.vue', 455 | }, 456 | }, 457 | }); 458 | 459 | const vm = mount(Vue, built); 460 | 461 | await sleep(100); 462 | expect(vm.$el.outerHTML).toBe('
Hello worlds!!!!!!
'); 463 | }, 2000); 464 | 465 | test('Resolver', async () => { 466 | const built = await build({ 467 | '/index.vue': outdent` 468 | 473 | `, 474 | '/HelloWorlds.vue': outdent` 475 | 478 | `, 479 | '/LoadingComponent.vue': outdent` 480 | 483 | `, 484 | '/ErrorComponent.vue': outdent` 485 | 488 | `, 489 | }, { 490 | components({ pascal }) { 491 | if (pascal === 'HelloWorld') { 492 | return { 493 | magicComments: ['webpackMode: "eager"'], 494 | component: '/HelloWorlds.vue', 495 | loading: '/LoadingComponent.vue', 496 | error: '/ErrorComponent.vue', 497 | }; 498 | } 499 | return undefined; 500 | }, 501 | }); 502 | 503 | const vm = mount(Vue, built); 504 | 505 | await sleep(100); 506 | expect(vm.$el.outerHTML).toBe('
Hello worlds!!!!!!
'); 507 | }, 2000); 508 | }); 509 | 510 | describe('Functional components', () => { 511 | test('Functional mode disabled', async () => { 512 | const built = await build({ 513 | '/index.vue': outdent` 514 | 517 | `, 518 | '/components/goodbye-world.vue': outdent` 519 | 522 | `, 523 | '/components/goodbye.vue': outdent` 524 | 527 | `, 528 | '/components/bye.vue': outdent` 529 | 532 | `, 533 | '/components/world.vue': outdent` 534 | 537 | `, 538 | }, { 539 | components: { 540 | GoodbyeWorld: '/components/goodbye-world.vue', 541 | Goodbye: '/components/goodbye.vue', 542 | Bye: '/components/bye.vue', 543 | World: '/components/world.vue', 544 | }, 545 | }); 546 | 547 | const vm = mount(Vue, built); 548 | expect(vm.$el.outerHTML).toBe('

'); 549 | }); 550 | 551 | test('Functional mode enabled', async () => { 552 | const built = await build({ 553 | '/index.vue': outdent` 554 | 557 | `, 558 | '/components/goodbye-world.vue': outdent` 559 | 562 | `, 563 | '/components/goodbye.vue': outdent` 564 | 567 | `, 568 | '/components/bye.vue': outdent` 569 | 572 | `, 573 | '/components/world.vue': outdent` 574 | 577 | `, 578 | }, { 579 | functional: true, 580 | components: { 581 | GoodbyeWorld: '/components/goodbye-world.vue', 582 | Goodbye: '/components/goodbye.vue', 583 | Bye: '/components/bye.vue', 584 | World: '/components/world.vue', 585 | }, 586 | }); 587 | 588 | const vm = mount(Vue, built); 589 | expect(vm.$el.outerHTML).toBe('

goodbye world

'); 590 | }); 591 | }); 592 | 593 | describe('Unused component detection', () => { 594 | test('Don\'t import fake component - Pascal', async () => { 595 | const built = await build({ 596 | '/index.vue': outdent` 597 | 602 | 613 | `, 614 | '/hello-world-real.vue': outdent` 615 | 618 | `, 619 | }, { 620 | components: { 621 | 'hello-world': '/hello-world-non-existent.vue', 622 | }, 623 | }); 624 | 625 | const vm = mount(Vue, built); 626 | expect(vm.$el.outerHTML).toBe('
hello world real
'); 627 | }); 628 | 629 | test('Don\'t import fake component - kebab', async () => { 630 | const built = await build({ 631 | '/index.vue': outdent` 632 | 637 | 646 | `, 647 | '/hello-world-real.vue': outdent` 648 | 651 | `, 652 | }, { 653 | components: { 654 | 'hello-world': '/hello-world-non-existent.vue', 655 | }, 656 | }); 657 | 658 | const vm = mount(Vue, built); 659 | expect(vm.$el.outerHTML).toBe('
hello world real
'); 660 | }); 661 | 662 | test('Won\'t detect registered', (cb) => { 663 | build({ 664 | '/index.vue': outdent` 665 | 670 | 681 | `, 682 | '/hello-world-real.vue': outdent` 683 | 686 | `, 687 | }, { 688 | components: { 689 | 'hello-world': '/hello-world-trap.vue', 690 | }, 691 | }).catch(() => { 692 | // Expect error 693 | cb(); 694 | }); 695 | }); 696 | }); 697 | -------------------------------------------------------------------------------- /test/utils.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | const path = require('path'); 3 | const webpack = require('webpack'); 4 | const { Volume } = require('memfs'); 5 | const fs = require('fs'); 6 | const { ufs } = require('unionfs'); 7 | const VueLoaderPlugin = require('vue-loader/lib/plugin'); 8 | 9 | const loaderPath = require.resolve('..'); 10 | 11 | const httpServer = (() => { 12 | let builtFs; 13 | 14 | const server = http.createServer((req, res) => { 15 | res.write(builtFs.readFileSync(req.url)); 16 | setTimeout(() => res.end(), 200); 17 | }); 18 | 19 | return { 20 | setFs(_builtFs) { 21 | builtFs = _builtFs; 22 | }, 23 | start() { 24 | return new Promise((resolve) => { 25 | this.listening = server.listen(0, resolve); 26 | }); 27 | }, 28 | get port() { 29 | return this.listening.address().port; 30 | }, 31 | stop() { 32 | return new Promise((resolve) => { 33 | server.close(resolve); 34 | }); 35 | }, 36 | }; 37 | })(); 38 | 39 | function build(volJson, loaderConfig = {}) { 40 | return new Promise((resolve, reject) => { 41 | const mfs = Volume.fromJSON(volJson); 42 | mfs.join = path.join.bind(path); 43 | 44 | const compiler = webpack({ 45 | mode: 'production', 46 | optimization: { 47 | minimize: false, 48 | providedExports: false, 49 | }, 50 | resolve: { 51 | alias: { 52 | '@': '/', 53 | }, 54 | }, 55 | resolveLoader: { 56 | alias: { 57 | 'vue-import-loader': loaderPath, 58 | }, 59 | }, 60 | module: { 61 | rules: [ 62 | { 63 | test: /\.vue$/, 64 | use: [ 65 | { 66 | loader: 'vue-import-loader', 67 | options: loaderConfig, 68 | }, 69 | { 70 | loader: 'vue-loader', 71 | options: { 72 | productionMode: true, 73 | }, 74 | }, 75 | ], 76 | }, 77 | ], 78 | }, 79 | plugins: [ 80 | new VueLoaderPlugin(), 81 | ], 82 | entry: '/index.vue', 83 | output: { 84 | path: '/dist-[hash]', 85 | publicPath: `http://localhost:${httpServer.port}/dist-[hash]/`, 86 | }, 87 | }); 88 | 89 | compiler.inputFileSystem = ufs.use(fs).use(mfs); 90 | compiler.outputFileSystem = mfs; 91 | 92 | compiler.run((err, stats) => { 93 | if (err) { 94 | reject(err); 95 | return; 96 | } 97 | 98 | if (stats.compilation.errors.length > 0) { 99 | reject(stats.compilation.errors); 100 | return; 101 | } 102 | 103 | httpServer.setFs(mfs); 104 | resolve(mfs.readFileSync(`/dist-${stats.hash}/main.js`).toString()); 105 | }); 106 | }); 107 | } 108 | 109 | function mount(Vue, src) { 110 | // eslint-disable-next-line no-eval 111 | const { default: Component } = eval(src); 112 | const vm = new Vue(Component); 113 | vm.$mount(); 114 | return vm; 115 | } 116 | 117 | module.exports = { 118 | httpServer, 119 | build, 120 | mount, 121 | }; 122 | --------------------------------------------------------------------------------