import and export all .vue files from the folder - javascript

I'm working on a VueJS project.
I have a folder with several single file components and I need to export all in one index.js
so I have this code
import a from './a.vue'
import b from './b.vue'
export {
a,
b
}
but I'd like to do this dynamically, so I do not have to change this index.js every time I create a new component
someone to help?

From this article, you could try this:
const requireModule = require.context(".", false, /\.vue$/); //extract vue files inside modules folder
const modules = {};
requireModule.keys().forEach(fileName => {
const moduleName = fileName.replace(/(\.\/|\.vue)/g, ""); //
modules[moduleName] = requireModule(fileName).default;
});
export default modules;

I created a library that does all this work, follow the link
named-exports

Related

How to use an external third party library in Stencil.js

I have a Stencil component and, as part of its business logic, I need to use an external Javascript file mylib.js. The Javascript file contains some business logic the Stencil component should use.
Here's my component:
import { Component, Element, Prop, h, Host } from '#stencil/core';
import moment from 'moment';
import mylib from 'src/js/mylib.js';
#Component({
tag: 'dashboard-widget',
styleUrl: 'dashboard-widget.css',
shadow: false
})
export class DashboardWidget {
#Element() el: HTMLElement;
#Prop() canvas: HTMLElement;
#Prop() channelName: string = "";
#Prop() channelValue: string = "";
#Prop() isBlinking: boolean = true;
componentDidLoad() {
console.log(mylib.test());
}
render() {
return (
<Host>
<div class="card-content card-content-padding">
<b>{this.channelName}</b>
<h1 class="dashboard-card-value">{this.channelValue}</h1>
<canvas class="dashboard-card-canvas"></canvas>
</div>
</Host>
);
}
}
I keep getting the error
TypeScript Cannot find module 'src/js/mylib.js'.
I tried:
import mylib from 'src/js/mylib.js';
import 'src/js/mylib.js';
import 'mylib' from 'src/js/mylib.js';
to no avail.
The mylib.js file is inside the js folder.
The online documentation doesn't mention at all how to import external libraries. I've been successful importing moment.js but only because I installed it first by doing:
npm install moment
and then importing it inside the component by doing:
import moment from 'moment';
I also tried to "import" the external JS library by referencing it inside the index.html
<script src="assets/js/mylib.js"></script>
The library is available outside the component but not inside it
Since you're mentioning Moment.js, I'll explain how to load that first. It's possible to do it the way you did by importing it inside your component's module, however that will result in a large bundle size because the npm package of moment is not targeted for browsers but for use in Node.js projects where bundle size doesn't matter. Moment.js distributes browser bundles inside the package though. So what you can do is add a copy task to your Stencil output target to copy node_modules/moment/min/moment.min.js into your build directory:
// stencil.config.ts
import { Config } from '#stencil/core';
export const config: Config = {
namespace: 'my-app',
outputTargets: [
{
type: 'www',
copy: [
{
src: '../node_modules/moment/min/moment.min.js',
dest: 'lib/moment.min.js'
}
]
}
]
};
Then, as you already tried with your lib, you can load that script in src/index.html:
<script src="/lib/moment.min.js"></script>
However, your Typescript project won't know yet that moment is available in the global scope. That's easy to solve though, you can just add a declaration file somewhere in your project, e. g. src/global.d.ts with the content
import _moment from 'moment';
declare global {
const moment: typeof _moment;
}
For your test files which run in the Node.js context, not a browser context, you can either import moment or also add moment to the global scope, by creating a file (e. g. jest-setup-file.js) with the content
global.moment = require('moment');
and then in stencil.config.ts you just add the setupFilesAfterEnv field to testing:
{
testing: {
setupFilesAfterEnv: ['<rootDir>/jest-setup-file.js']
}
}
If you don't need the script in your whole application but only when a specific component is loaded, it makes more sense to only load the script from within that component. The easiest way to do that is to create a script element and add it to the DOM:
declare const MyLib: any; // assuming that `mylib.js` adds `MyLib` to the global scope
export class MyComp {
componentWillLoad() {
const src = "assets/js/mylib.js";
if (document.querySelector(`script[src="${src}"]`)) {
return; // already exists
}
const script = document.createElement('script');
script.src = src;
document.head.appendChild(script);
}
}
Your script/library will most likely also contribute a variable to the global scope, so you'll have to let Typescript know again, which you can do using the declare keyword to declare that a variable exists in the global context (see https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html#global-variables).
As another example, here's a helper I wrote to load the google maps api:
export const importMapsApi = async () =>
new Promise<typeof google.maps>((resolve, reject) => {
if ('google' in window) {
return resolve(google.maps);
}
const script = document.createElement('script');
script.onload = () => resolve(google.maps);
script.onerror = reject;
script.src = `https://maps.googleapis.com/maps/api/js?key=${googleApiKey}&libraries=places`;
document.body.appendChild(script);
});
(The google type comes from the #types/googlemaps package)
I can then use this like
const maps = await importMapsApi();
const service = new maps.DistanceMatrixService();
To import files that aren't installed by NPM you can use relative paths prefixed with ./ or ../:
import mylib from '../../js/mylib.js';
You can import everything that is exported from that JS file and even use named imports:
mylib.js
export function someFunction() {
// some logic
}
dashboard-widget.tsx
import { someFunction } from '../../js/mylib.js`;
const result = someFunction();

Dynamic export of variables ES5 to ES6

I'm working on a vue/nuxt.js project and would like to apply the atomic design methodology, i would like to import the components in a clustered and smarter way.
currently
import ButtonStyled from '#/components/atoms/ButtonStyled.vue'
import TextLead from '#/components/atoms/TextLead.vue'
import InputSearch from '#/components/atoms/InputSearch.vue'
How I wish
import {
ButtonStyled,
TextLead,
InputSearch
} from '#/components/atoms'
Solution?
index.js in folder of atoms
it works perfectly (ES5)
// ES5 works 👍
const req = require.context('.', false, /\.vue$/)
req.keys().forEach(fileName => {
const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
module.exports[componentName] = req(fileName).default
})
// ES6 does not work 👎
// ERROR: Module build failed, 'import' and 'export' may only appear at the top level
const req = require.context('.', false, /\.vue$/)
req.keys().forEach(fileName => {
const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
export const [componentName] = req(fileName).default
})
nuxt use ES6
NOTE: I can not export an object because I can not use import {ButtonStyled} or I will have to de-structure the object after importing it
I need to export so that I can use
import { ButtonStyled } from '#/components/atoms'
I need to export name of each component in the folder
Any advice, information or suggestions will be appreciated.
Thanks in advance.
Well first of all you need to be careful when making use of import/export on EM6, since now you can't export anywhere outside of the top level scope of the js file and the general treatment of it is different than in EM5.
Now with the problem. I see you are exporting the components from inside of a ForEach loop/function and that works totally fine in EM5 but with EM6 It's different, and at least I see two ways you can solve the problem if you aren't expecting the number of components to grow dinamically:
Call a function that returns the component and export it, do it for each component. Should look something like this:
./componentsFile.js
exports.component1 = () => { /*code...*/ return component }
exports.component2 = () => { /*code...*/ return component }
./renderingFile.js
import { component1, component2 } from './componentsFile.js'
/* use the components that you get from the return... */
The other way is to build an object which fields are the components. And destructure it when you are importing.
./componentsFile.js
const component1 = /*Create the component*/
const component2 = /*Create the component*/
exports.object = {
component1,
component2,}
./renderingFile.js
import { component1, component2 } from './componentsFile.js'
/*Use the components...*/
I think you can get the idea with this two ways.
I created a library that solved this problem for me, makes exports named from a directory and listens to the creation, rename and exlclusion of the modules and updates the index.js that does the export.
Maybe it helps other people.
named-exports

Dynamic Vue Import from a subfolder

I am trying to import all .vue files in a certain subfolder into another component. I know about Global registration of Base components but this does not seem to help me here.
Let's say I have default Vue component (not the main one) with something like this:
export default {
components: {
red: () => import('./panes/red'),
},
data() {
return {
current: false,
};
},
and my file structure is something like:
/src
- main.js
- main.vue
-- components/
-- panes/
--- /red.vue
--- /green.vue
--- /blue.vue
-- SubMain.vue
I am trying to dynamically create the components object for the SubMain.vue folder.
So I try something like this in SubMain.vue:
import myComponents from './src/components/panes';
...
components: Object.keys(myComponents).reduce((obj, name) => {
return Object.assign(obj, { [name]: () => import(myComponents[name]) })
}, {}),
But eslint is giving me errors about Missing file extension and Unable to resolve path to module on the myComponents variable. Yes, I double checked my path and tried other paths. Nothing. I am using the Vue CLI 3 project.
If you're using Webpack, you can use require.context:
import _kebabCase from lodash/kebabCase
const components = require.context('src/panes', true)
components.keys().map(component => {
// turn './ComponentName.vue' into 'component-name'
const componentName = _kebabCase(
component.replace(/^\.\//, '').replace(/\.vue$/, '')
)
// register new component globally
Vue.component(componentName, components(component))
})
I don't think you can import multiple components that way without an index file that aggregates the component import/exports for you. See Import multiple components in vue using ES6 syntax doesn't work

In React-native Js files how can we get without folder paths is It possible?

i am developing one sample implemented Project, in this project some js files getting from paths like ./../folder/file.js and some files getting from folders like 'myfile' here second way when will we get like this.
i am confusing this second way any one clarify this .
here i am attached image please check it once image.
Suppose you have following files
app
/constants
StringConstants.js
/utils
StringHelper.js
StringConstants.js
export const DONE_BUTTON_LABEL='DONE';
export const CREATE_ALERT= 'Create Email Alert';
export const CREATE= 'CREATE';
export const CANCEL= 'Cancel';
StringHelper.js
class StringHelper {
...
}
export default new StringHelper();
How to import? See following examples
import StringHelper '../utils/StringHelper';
import * as StringConstants from '../utils/StringConstants';
//You just imported all constants from StringConstants file. Use it as StringConstants.DONE_BUTTON_LABEL or StringConstants.CREATE
import {CREATE_ALERT} StringConstants from '../utils/StringConstants';
//import CREATE_ALERT constant from StringConstants file.

Angular 2: exporting an export into a component file

In my Angular 2 app, I have a settings.js file with various exports that I want to use throughout the application:
exports.httpPort = 9000;
exports.httpsPort = 1435;
exports.segmentID = 1;
I want to export some of these into my ts component file query.component.ts, but I'm at a loss on what the correct syntax to do so is.
I see that many .js files have something along the lines of
var settings = require('../../settings');
which grabs the settings file and then
settings.dbConfig
Which calls the export, but it doesn't work on my component file.
This is my project file structure:
component.ts
- project/web/src/app/component.ts
-Place where I want to import an export from settings.js.
settings.js - project/server/settings.js
-File where I want to make the export.
In the component class you can do:
...
import {httpPort} from "../../../server/settings.js"
...

Categories

Resources