With ES6, I can import several exports from a file like this:
import {ThingA, ThingB, ThingC} from 'lib/things';
However, I like the organization of having one module per file. I end up with imports like this:
import ThingA from 'lib/things/ThingA';
import ThingB from 'lib/things/ThingB';
import ThingC from 'lib/things/ThingC';
I would love to be able to do this:
import {ThingA, ThingB, ThingC} from 'lib/things/*';
or something similar, with the understood convention that each file contains one default export, and each module is named the same as its file.
Is this possible?
I don't think this is possible, but afaik the resolution of module names is up to module loaders so there might a loader implementation that does support this.
Until then, you could use an intermediate "module file" at lib/things/index.js that just contains
export * from 'ThingA';
export * from 'ThingB';
export * from 'ThingC';
and it would allow you to do
import {ThingA, ThingB, ThingC} from 'lib/things';
Just a variation on the theme already provided in the answer, but how about this:
In a Thing,
export default function ThingA () {}
In things/index.js,
export {default as ThingA} from './ThingA'
export {default as ThingB} from './ThingB'
export {default as ThingC} from './ThingC'
Then to consume all the things elsewhere,
import * as things from './things'
things.ThingA()
Or to consume just some of things,
import {ThingA,ThingB} from './things'
The current answers suggest a workaround but it's bugged me why this doesn't exist, so I've created a babel plugin which does this.
Install it using:
npm i --save-dev babel-plugin-wildcard
then add it to your .babelrc with:
{
"plugins": ["wildcard"]
}
see the repo for detailed install info
This allows you to do this:
import * as Things from './lib/things';
// Do whatever you want with these :D
Things.ThingA;
Things.ThingB;
Things.ThingC;
again, the repo contains further information on what exactly it does, but doing it this way avoids creating index.js files and also happens at compile-time to avoid doing readdirs at runtime.
Also with a newer version you can do exactly like your example:
import { ThingsA, ThingsB, ThingsC } from './lib/things/*';
works the same as the above.
You now can use async import():
import fs = require('fs');
and then:
fs.readdir('./someDir', (err, files) => {
files.forEach(file => {
const module = import('./' + file).then(m =>
m.callSomeMethod();
);
// or const module = await import('file')
});
});
Great gugly muglys! This was harder than it needed to be.
Export one flat default
This is a great opportunity to use spread (... in { ...Matters, ...Contacts } below:
// imports/collections/Matters.js
export default { // default export
hello: 'World',
something: 'important',
};
// imports/collections/Contacts.js
export default { // default export
hello: 'Moon',
email: 'hello#example.com',
};
// imports/collections/index.js
import Matters from './Matters'; // import default export as var 'Matters'
import Contacts from './Contacts';
export default { // default export
...Matters, // spread Matters, overwriting previous properties
...Contacts, // spread Contacts, overwriting previosu properties
};
// imports/test.js
import collections from './collections'; // import default export as 'collections'
console.log(collections);
Then, to run babel compiled code from the command line (from project root /):
$ npm install --save-dev #babel/core #babel/cli #babel/preset-env #babel/node
(trimmed)
$ npx babel-node --presets #babel/preset-env imports/test.js
{ hello: 'Moon',
something: 'important',
email: 'hello#example.com' }
Export one tree-like default
If you'd prefer to not overwrite properties, change:
// imports/collections/index.js
import Matters from './Matters'; // import default as 'Matters'
import Contacts from './Contacts';
export default { // export default
Matters,
Contacts,
};
And the output will be:
$ npx babel-node --presets #babel/preset-env imports/test.js
{ Matters: { hello: 'World', something: 'important' },
Contacts: { hello: 'Moon', email: 'hello#example.com' } }
Export multiple named exports w/ no default
If you're dedicated to DRY, the syntax on the imports changes as well:
// imports/collections/index.js
// export default as named export 'Matters'
export { default as Matters } from './Matters';
export { default as Contacts } from './Contacts';
This creates 2 named exports w/ no default export. Then change:
// imports/test.js
import { Matters, Contacts } from './collections';
console.log(Matters, Contacts);
And the output:
$ npx babel-node --presets #babel/preset-env imports/test.js
{ hello: 'World', something: 'important' } { hello: 'Moon', email: 'hello#example.com' }
Import all named exports
// imports/collections/index.js
// export default as named export 'Matters'
export { default as Matters } from './Matters';
export { default as Contacts } from './Contacts';
// imports/test.js
// Import all named exports as 'collections'
import * as collections from './collections';
console.log(collections); // interesting output
console.log(collections.Matters, collections.Contacts);
Notice the destructuring import { Matters, Contacts } from './collections'; in the previous example.
$ npx babel-node --presets #babel/preset-env imports/test.js
{ Matters: [Getter], Contacts: [Getter] }
{ hello: 'World', something: 'important' } { hello: 'Moon', email: 'hello#example.com' }
In practice
Given these source files:
/myLib/thingA.js
/myLib/thingB.js
/myLib/thingC.js
Creating a /myLib/index.js to bundle up all the files defeats the purpose of import/export. It would be easier to make everything global in the first place, than to make everything global via import/export via index.js "wrapper files".
If you want a particular file, import thingA from './myLib/thingA'; in your own projects.
Creating a "wrapper file" with exports for the module only makes sense if you're packaging for npm or on a multi-year multi-team project.
Made it this far? See the docs for more details.
Also, yay for Stackoverflow finally supporting three `s as code fence markup.
Similar to the accepted answer but it allows you to scale without the need of adding a new module to the index file each time you create one:
./modules/moduleA.js
export const example = 'example';
export const anotherExample = 'anotherExample';
./modules/index.js
// require all modules on the path and with the pattern defined
const req = require.context('./', true, /.js$/);
const modules = req.keys().map(req);
// export all modules
module.exports = modules;
./example.js
import { example, anotherExample } from './modules'
If you are using webpack. This imports files automatically and exports as api namespace.
So no need to update on every file addition.
import camelCase from "lodash-es";
const requireModule = require.context("./", false, /\.js$/); //
const api = {};
requireModule.keys().forEach(fileName => {
if (fileName === "./index.js") return;
const moduleName = camelCase(fileName.replace(/(\.\/|\.js)/g, ""));
api[moduleName] = {
...requireModule(fileName).default
};
});
export default api;
For Typescript users;
import { camelCase } from "lodash-es"
const requireModule = require.context("./folderName", false, /\.ts$/)
interface LooseObject {
[key: string]: any
}
const api: LooseObject = {}
requireModule.keys().forEach(fileName => {
if (fileName === "./index.ts") return
const moduleName = camelCase(fileName.replace(/(\.\/|\.ts)/g, ""))
api[moduleName] = {
...requireModule(fileName).default,
}
})
export default api
I've used them a few times (in particular for building massive objects splitting the data over many files (e.g. AST nodes)), in order to build them I made a tiny script (which I've just added to npm so everyone else can use it).
Usage (currently you'll need to use babel to use the export file):
$ npm install -g folder-module
$ folder-module my-cool-module/
Generates a file containing:
export {default as foo} from "./module/foo.js"
export {default as default} from "./module/default.js"
export {default as bar} from "./module/bar.js"
...etc
Then you can just consume the file:
import * as myCoolModule from "my-cool-module.js"
myCoolModule.foo()
Just an other approach to #Bergi's answer
// lib/things/index.js
import ThingA from './ThingA';
import ThingB from './ThingB';
import ThingC from './ThingC';
export default {
ThingA,
ThingB,
ThingC
}
Uses
import {ThingA, ThingB, ThingC} from './lib/things';
Nodejs ? Do like this:
Create a folder with index.js, in index file, add this:
var GET = require('./GET');
var IS = require('./IS');
var PARSE = require('./PARSE');
module.exports = { ...GET, ...IS, ...PARSE};
And, in file GET.js, or IS.js export as normal:
module.exports = { /* something as you like */}
ANd now, you need only including index.js like:
const Helper = require('./YourFolder');
Helper will include all of function in YourFolder.
Good day!
This is not exactly what you asked for but, with this method I can Iterate throught componentsList in my other files and use function such as componentsList.map(...) which I find pretty usefull !
import StepOne from './StepOne';
import StepTwo from './StepTwo';
import StepThree from './StepThree';
import StepFour from './StepFour';
import StepFive from './StepFive';
import StepSix from './StepSix';
import StepSeven from './StepSeven';
import StepEight from './StepEight';
const componentsList= () => [
{ component: StepOne(), key: 'step1' },
{ component: StepTwo(), key: 'step2' },
{ component: StepThree(), key: 'step3' },
{ component: StepFour(), key: 'step4' },
{ component: StepFive(), key: 'step5' },
{ component: StepSix(), key: 'step6' },
{ component: StepSeven(), key: 'step7' },
{ component: StepEight(), key: 'step8' }
];
export default componentsList;
You can use require as well:
const moduleHolder = []
function loadModules(path) {
let stat = fs.lstatSync(path)
if (stat.isDirectory()) {
// we have a directory: do a tree walk
const files = fs.readdirSync(path)
let f,
l = files.length
for (var i = 0; i < l; i++) {
f = pathModule.join(path, files[i])
loadModules(f)
}
} else {
// we have a file: load it
var controller = require(path)
moduleHolder.push(controller)
}
}
Then use your moduleHolder with dynamically loaded controllers:
loadModules(DIR)
for (const controller of moduleHolder) {
controller(app, db)
}
I was able to take from user atilkan's approach and modify it a bit:
For Typescript users;
require.context('#/folder/with/modules', false, /\.ts$/).keys().forEach((fileName => {
import('#/folder/with/modules' + fileName).then((mod) => {
(window as any)[fileName] = mod[fileName];
const module = new (window as any)[fileName]();
// use module
});
}));
if you don't export default in A, B, C but just export {} then it's possible to do so
// things/A.js
export function A() {}
// things/B.js
export function B() {}
// things/C.js
export function C() {}
// foo.js
import * as Foo from ./thing
Foo.A()
Foo.B()
Foo.C()
I try to make news web apps to use newsapi.org.
I wanted to hide my api_key so I decided to use env property in Nuxt.Js.
But now I got 401 status code from server.
first of all, I made the .env file in project file and I put my API_KEY.
and then I installed 'dotenv' use 'yarn add dotenv' command in VSCode terminal.
and I add nuxt.config.ts file. I have used TypeScript in my project so all file depend on TypeScript.
require('dotenv').config()
const { API_KEY } = process.env
export default {
~~~~~~~~~~
env: {
API_KEY,
},
}
and I used Vuex to get news information.
so I made code like following.
~/store/getNews.ts
import { MutationTree, ActionTree, GetterTree } from "vuex";
import axios from "axios";
const url = 'http://newsapi.org/v2/top-headlines';
interface RootState { }
export interface NewsArticles {
source?: {}
author?: string
title?: string
description?: string
url?: any
urlToImage?: any
publishedAt?: string
content?: string
}
interface State {
newArticle: NewsArticles
}
export const state = () => ({
newsArticle: []
})
export const getters: GetterTree<State, RootState> = {
newsArticle: (state: State) => state.newArticle
}
export const mutations: MutationTree<State> = {
setNewsArticle: (state: State, newsArticle: NewsArticles) => {
state.newArticle = newsArticle
}
}
export const actions: ActionTree<State, RootState> = {
getNewsArticle: async ({ commit },{params}) => {
try{
const data = await axios.get(url,{params})
commit('setNewsArticle', data.data.articles)
}catch(error){
commit('setNewsArticle',[])
}
}
}
export default { state, getters, mutations, actions }
and finally, I made vue file to show the news information like following.
<template>
<div>
<p>this is NewsApi test pages!!</p>
<ul v-for="(item, index) in items" :key="index">
<li>{{ item.title }}</li>
</ul>
</div>
</template>
<script lang="ts">
import { Component, namespace, Vue } from 'nuxt-property-decorator'
import { NewsArticles } from '~/store/getNews'
const getNews = namespace('getNews')
#Component({})
export default class extends Vue {
#getNews.Action getNewsArticle!: Function
#getNews.Getter newsArticle!: NewsArticles
items: any = []
async mounted() {
await this.getNewsArticle({
params: { country: 'jp', category: 'business', apiKey: process.env.API_KEY },
})
this.items = this.newsArticle
}
}
</script>
I ran my app but I got 401 status code and I checked the console error like following.
{status: "error", code: "apiKeyInvalid",…}
code: "apiKeyInvalid"
message: "Your API key is invalid or incorrect. Check your key, or go to https://newsapi.org to create a free API key."
status: "error"
I don't know why that error occurred.
I checked apikey correctly setting to confirm consle.log.
in index.vue
<script lang='ts'>
~~~~
export default class extend Vue{
mounted(){
console.log(process.env.API_KEY)
}
}
</script>
You don't need to call require('dotenv').config(), as Nuxt automatically invokes it.
Also, for the env vars to be available in the production build, their names must be prefixed with NUXT_ENV_ (i.e., NUXT_ENV_API_KEY). Note this allows you to keep the key from being checked into source (assuming your .env file is also kept out of source control), but your API key can still be observed in the Network tab in DevTools.
I have to display dynamic meta descriptions for my articles and I am kind of struggling to achieve that with the async function for my head object. This is what I have so far:
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
#Component
export default class ArticleContent extends Vue {
article: any | null = null;
articlelist = example.data;
async asyncData({params: any }) { <----- Not sure how I could put in my articlelist here
return this.articlelist;
}
head(): object {
return {
title: this.articlelist.productId.productNames['en'],
meta: [
{
hid: this.articlelist._id,
name: this.articlelist.productNames['en'],
content: this.articlelist.metaDescription['en'],
},
],
};
}
}
</script>
articlelist is what I am using in the head() object for my meta description. Would appreciate some help!
Both the head() and asyncData() properties are not part of the core of vue,
to use head() you need to install this as a plugin
to use asyncData() you have to use nuxt
If your spa has a strong need for seo I suggest you use nuxt, which natively includes seo and the conversion from vue to nuxt is very easy
If you already using nuxt this is the correct way to get
async asyncData({params: any }) {
const articlelist = await axios.get('some.url'); //get the data
return { articlelist }; //this object is merged with the data of the istance
}
I am refactoring some code in my app and turns out,the below logic it is repeated in many many components.
import component1 from '...'
import component2 from '...'
import component3 from '...'
//...many others
export default {
//other data
components: {
component1,
component2,
component3
//...
}
}
Does exists a shorter approach in order to clean my code?
Thanks for your time
Below are 3 ways.I prefer method 3 by the way.
Method 1
Create a js file in my case dynamic_imports.js:
export default function (config) {
let registered_components = {}
for (let component of config.components) {
registered_components[component.name] = () => System.import(`../${config.path}/${component.file_name}.vue`)
}
return registered_components
}
In the component in which you have many component imports and registrations
import dynamic_import from '#/services/dynamic_imports' //importing the above file
let components = dynamic_import({
path: 'components/servers',
components: [
{ name: 'server-one', file_name: 'serverOne' },
{ name: 'server-two', file_name: 'serverTwo' },
]
})
export default {
//...other code
components: components
}
As a result you will import and register your components with "clean code".
But note that this worked for me,maybe it has to modified a lit bit to fit your needs,to understand:
The property path means that will look at this path for the names specified in file_name.The name property is the name you register the component
Method 2
If you don't like the above look below to another way:
function import_component(cmp_name){
return System.import(`#/components/${cmp_name}.vue`);
}
export default{
components: {
'component1': () => import_component('componentOne'),
'component2': () => import_component('componentTwo'),
'component3': () => import_component('componentThree')
}
}
Method 3
If again you are saying: This is not a cleaner way,take a look below but keep in mind that if you are working in team and skills differ,then some programmers will be a little bit confused.
dynamic_imports.js
export default function ({path, file_names, component_names}) {
let registered_components = {}
for (let [index, file_name] of file_names.entries()) {
registered_components[component_names[index]] = () => System.import(`../${path}/${file_name}.vue`)
}
return registered_components
}
In your component
import dynamic_import from '#/services/dynamic_imports'
let components = dynamic_import({
path: 'components/servers',
file_names: ['serverOne', 'serverTwo'],
component_names: ['server-one', 'server-two']
})
export default {
components: components
}
You can automatically register such repeated base components globally using the pattern described in the official docs
https://v2.vuejs.org/v2/guide/components-registration.html#Automatic-Global-Registration-of-Base-Components
Chris Fritz also talks about this pattern in his awesome video where he mentions 7 secret patterns for cleaner code and productivity boost while working with Vue.js
The disadvantage of this approach, however, is that the components that you autoregister this way always end up in the main bundle and therefore cannot be lazy loaded/code-splitted. So make sure you do this only for the base components that are very generic.
A vue application I am working on currently has lots of code redundancies relating to date functions. In an effort to reduce these redundancies, I'd like to create a utility class as shown below, import it and set it to a Vue data property within the component, so I can call the date functions within it.
I am not certain on the best way to implement this. The current implementation results in an error saying TypeError: this.dates is undefined and my goal is not only to resolve this error but create/utilize the class in the Vue environment using best standards.
Importing utility class
import Dates from "./utility/Dates";
...
Component
const contactEditView = Vue.component('contact-edit-view', {
data() {
return {
contact: this.myContact
dates: Dates
}
},
...
Dates.js
export default {
dateSmall(date) {
return moment(date).format('L');
},
dateMedium(date) {
return moment(date).format('lll');
},
dateLarge(date) {
return moment(date).format('LLL');
}
};
View
Date of Birth: {{ dates.dateMedium(contact.dob) }}
My suggestion for this is to use a plugin option in Vue. About Vue plugin
So you will crate a new folder called services, add file yourCustomDateFormater.js:
const dateFormater = {}
dateFormater.install = function (Vue, options) {
Vue.prototype.$dateSmall = (value) => {
return moment(date).format('L')
}
Vue.prototype.$dateMedium = (value) => {
return moment(date).format('lll')
}
}
In main.js:
import YourCustomDateFormater from './services/yourCustomDateFormater'
Vue.use(YourCustomDateFormater)
And you can use it anywhere, like this:
this.$dateSmall(yourValue)
Or, if you want to use mixin. Read more about mixin
Create a new file dateFormater.js
export default {
methods: {
callMethod () {
console.log('my method')
}
}
}
Your component:
import dateFormater from '../services/dateFormater'
export default {
mixins: [dateFormater],
mounted () {
this.callMethod() // Call your function
}
}
Note: "Use global mixins sparsely and carefully, because it affects every single Vue instance created, including third party components. In most cases, you should only use it for custom option handling like demonstrated in the example above. It’s also a good idea to ship them as Plugins to avoid duplicate application." - Vue documentation
dateUtilsjs
import moment from 'moment-timezone'
function formatDateTime(date) {
return moment.utc(date).format("M/D/yyyy h:mm A")
}
export { formatDateTime }
Component JS
...
import { formatDateTime } from '../utils/dateUtils'
...
methods: {
formatDateTime,
}
Used within component
{{ formatDateTime(date) }}