[Vuejs]-Using functions defined inside vue distributed file

1๐Ÿ‘

โœ…

Unless the function is exported, you cannot use that function via import.

Before you try to import you need to understand bundle resolution rules and check what kind of file it is:

// ES Module
export function toObject(arr) { /* */ }

// Common.js Module
module.exports.toObject = function toObject(arr) { /* */ }

// Global/UMD
window.toObject = function toObject(arr) { /* */ }

Typically, the module bundler will figure out the type of module and allow you to use import statement in you code like:

import { toObject } from 'vue';

Module bundler like Webpack uses main or module field in the package.json file of the package to determine the actual file to use. So if your dist folder contains multiple files, the bundler knows exactly which file to pick up.

Also, if you want to import from a file that is not specified in main or module field, then use can use package relative paths. For example, your dist folder has two files: โ€“ vue.js and helper.js and the main field is set to dist/vue.js, then saying just import * as x from 'vue' will always import from dist/vue.js file.

However, if you need to import from helper.js file, then use something like:

import * as x from 'vue/dist/helper.js';
import { something } from 'vue/dist/helper.js';

Again, import is possible only if given function or value is exported by that file (using any of module/commonjs/global exports). In your case, the function is not exported outside as we can see from the code and hence, you cannot import it and use it in your code.

As a workaround, you can simply copy the code and use it in your application.

๐Ÿ‘คHarshal Patil

Leave a comment