How to import a function to a Vue component? - javascript

I am trying to import a single function to my Vue component. I've created a separated js file for my function:
randomId.js:
exports.randomId = () => //My function ...
In my Vue component, I've imported the Random js:
let randomId = require('../functions/randomId');
randomId();
but Webpack throws an error of "randomId is not a function".
I tried to import the file using import syntax, but the error remains.
import randomId from '../functions/randomId';
Should I use some other methods for importing single functions? I'm relatively new to Webpack and JS6.

Change your function module to properly use ES6 export:
export function randomId() { /*My function ...*/ }
And then use ES6 named import:
import { randomId } from '../functions/randomId';

If you want to use CommonJS, then in the file with your randomId function do the following:
function randomId() {
...
}
module.exports = randomId;
And then the let randomId = require('../functions/randomId'); in your Vue component will work.

Related

import module.fucntion working but import { function } from '../../module' not working in ReactJS

Having some import issues, basically if I do something like:
import module from '../../module'
console.log(module.func)
This prints out the function which is expected behaviour however if I do this:
import { func } from '../../module'
console.log(func)
It prints out undefined.
I'm not exactly using it this way but am calling the function. However using the second import method, I get a uncaught TypeError: object(...) is not a function
Things to note: "func" is located in index.jsx of folder "module" along with some other functions so I can't use import * . It has also been exported.
I'm not sure why React is unable to find the functions inside the file using the second method, any help/explanation at all would be appreciated.
Edit:
This is how I'm exporting the function:
const func = (param, param) => {
....
return result
};
const func1 = (param, param) => {...}
.
.
.
export default{
func,
func1,
func2,
...
};
I'm guessing you're exporting the function not the way you're supposed to. Your function should look something like this:
export const func = () => {
// Code.
};
Importing it would look like this:
import { func } from '[path]'

Loop Javascript Imports to load into VuexORM

Anytime I have a long list of items to import in javascript my natural intention is to export those items in a separate file, require that file in my main javascript file, then if they need to be loaded into Vue or some other process, loop through them and load them dynamically.
I'm just getting started with VueORM, and ORM Models need to be loaded into the VueORM instance like so:
import Foo from '#/models/foo'
import Bar from '#/models/bar'
database.register(Foo)
database.register(Bar)
My app will have dozens of models so I'd like to export those from a single file as I mentioned, then loop through them and register them.
// main.js
import * as models from '#/models'
Object.keys(models).forEach(key => {
database.register(model[key])
})
In my models I'm exporting each as a function like so:
// models/index.js
export const Foo = () => import('#models/foo')
export const Bar = () => import('#models/bar')
This normally works fine, but in VuexORM the models are not being loaded.
Can someone please advise on a better method to load these Models from a separate file?
Vuex ORM does not handle dynamic imports. Rather than export them as dynamic imports, simply export them using the ordinary ESM syntax?
The following assumes your models are default exports.
// models/index.js
export { default as Foo } from '#/models/foo'
export { default as Bar } from '#/models/bar'
Subsequently, your main.js can aggregate the modules:
// main.js
import * as models from '#/models'
Object.values(models).forEach(model => database.register(model))
If you have Vite you can now do this. Taken from Quasar app.
//store/OrmModelPlugin.js
import { Database, install } from '#vuex-orm/core'
export default function () {
//Require all js files in our models directory
const database = new Database()
const modelFileContext = import.meta.globEager('src/models/*.js')
Object.values(modelFileContext).forEach(modelImport => {
const model = modelImport.default
database.register(model)
})
return install(database)
}
//store/index.js
import { store } from 'quasar/wrappers'
import { createStore } from 'vuex'
import OrmModelPlugin from './OrmModelPlugin'
export default store(function () {
const Store = createStore({
plugins: [OrmModelPlugin()],
})
return Store
})

How can I dynamically export components in index.js?

I'm working on a project with nuxt.js and I want to implement the atomic design methodology
so I currently import the components like this
import ButtonStyled from '#/components/atoms/ButtonStyled.vue'
import TextLead from '#/components/atoms/TextLead.vue'
import InputSearch from '#/components/atoms/InputSearch.vue'
but I need to import like this
import {
ButtonStyled,
TextLead,
InputSearch
} from '#/components/atoms'
the closer I got was that,
/atoms/index.js
const req = require.context('./', true, /\.vue$/)
const modules = {}
req.keys().forEach(fileName => {
const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
modules[componentName] = req(fileName).default
})
export const { ButtonStyled, TextLead } = modules
but I'm still defining the export variable names statically, I need to define dynamics based on the components inside the folder
NOTE: I can not use
export default modules
if I use the above code snippet I will not be able to import the way I need it, which is:
import { ButtonStyled } from "#/components/atoms"
require.context is a quite obscure function in Webpack, you will have issues while running unit tests. But, to solve your problem; You will need to import the index.js file in the main.js of your project.
This is how I do it:
_globals.js
// Globally register all base components prefixed with _base for convenience, because they
// will be used very frequently. Components are registered using the
// PascalCased version of their file name.
import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
const requireComponent = require.context('.', true, /_base-[\w-]+\.vue$/)
requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName)
const componentName = upperFirst(
camelCase(fileName.replace(/^\.\/_base/, '').replace(/\.\w+$/, ''))
)
Vue.component(componentName, componentConfig.default || componentConfig)
})
components/index.js
//...
import './_globals'
//...
main.js
//...
import './components' // This imports in the index.js
//...
This way your components loaded in with require.context() gets registered as a vue component and made globally available. I advice to only use global components with components that will be used a lot. Do not load a component globally if you intend to use it only one time.
You can find a working example here -> https://github.com/IlyasDeckers/vuetiful/tree/master/src
To get your unit tests working with jest, you will need to mock require.context(). This was a true pain, but can be achieved easily by using babel-plugin-transform-require-context
I try to use your way to do that, and known you have make a mistake at module.exports
module.exports can not use import , i think you may can do like this
at atoms/index.js
const req = require.context("./", true, /\.vue$/);
const atoms = {};
req.keys().forEach(fileName => {
const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, "$1");
atoms[componentName] = req(fileName).default;
});
export default atoms;
at where to use
import k from "#/components/atoms/index.js";
export default {
components: {
test1: k.test1,
test2: k.test2
}
};
or index.js
import test1 from "./test1.vue";
import test2 from "./test2.vue";
export { test1, test2 };
and where to use like this
import {test1,test2} from "#/components/atoms/index.js";
export default {
components: {
test1,
test2
}
};
I created a library that does all this for me, maybe it helps other people.
named-exports

export default arrow function cannot be imported

I'm using React, and I have something like this in my code:
renderDetails.js:
export default renderDetails = (details) => {
// function logic removed for brevity
}
Then, in the same folder, I have another source file from where I want to import it, and I do something like this:
businessDetails.js:
import renderDetails from './renderDetails';
// rest removed for brevity
But, I get an error message pointing to my renderDetails.js file and says: "rederDetails is not defined". Any ideas what the problem might be and how to fix it?
The problem is that even though you are exporting the component as default you are giving it a name which is not defined
You can either do
export default (details) => {
}
or
const renderDetails = (details) => {
}
export default renderDetails;
One more thing, when you are trying to render components, make sure that their name starts with a Uppercase character.
try that way.
functions.jsx
export function renderDetails(details) => {
// function logic removed for brevity
}
then import like,
import { renderDetails } from './functions';
P.S.
./ is for if both files a re in same namespace/folder.
You can also write them like this:
export const exampleFunctionOne = () => {}
export const exampleFunctionTwo = () => {}
Then import the individual functions you require from said file like this:
import { exampleFunctionOne, exampleFunctionTwo } from './exampleFile';
I like this approach when wanting to combine similar functions into one file such as validators or filters making them easy to import and use across your application.

ReactJS: Uncaught ReferenceError: require is not defined

I'm trying to use DRY in React JS. I'm trying to use the same HTML partial in different files
partial:
var AdminMenu = React.createClass({
getInitialState: function() {
return {};
},
render: function() {
return (
<h1>Menu</h1>
);
}
});
I'm requeiring it in another file:
require('./scripts/adminMenu.js');
ReactDOM.render(
<AdminMenu/>,
document.getElementById('content')
);
But I'm getting an error:
Uncaught ReferenceError: require is not defined
this scripts are included on html page like:
<script type="text/babel" src="scripts/admin.js"></script>
I'm using webpack
If you are not using any module bundler like webpack or etc.
You should assign you components to some javascript global object, because objects from .jsx are not put in global scope
So here is the solution (used window object here)
Defined module:
window.AdminMenu = React.createClass({
getInitialState: function() {
return {};
},
render: function() {
return (
<h1>Menu</h1>
);
}
});
Where you use it:
ReactDOM.render(
<window.AdminMenu/>,
document.getElementById('content')
);
You have to use
const { Component } = React;
const { render } = ReactDOM;
in place of
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
Consider to use ES6 modules instead of require with React
export a module:
// src/hello.js
// export as default
export default const hello = ({name}) => (
<h1>Hello {name}</h1>
)
import a module:
// src/index.js
// import from relative directory (src)
import Hello from './hello'
const App = () => {
return (
<div>
<Hello name="Pavel" />
</div>
)
}
You should read more about modules for example here: https://www.sitepoint.com/understanding-es6-modules/
The main problems in your existing code are:
It looks, in spite of that you are using Webpack, you use it wrong way. In your final bundle (final JS file), it shouldn't contain any 'require' keywords. Did you use Babel with your webpack? Please, show us your WebPack config.
Your AdminMenu file looks not like module. Your adminMenu file should contain 'export' keyword, after that you will be able to 'require' or 'import' it from other files.
Also, you can write questions in comments with Russian if it is more convenient for you

Categories