I am trying to achieve Vue.js dynamic async component registration. This video gave me code that works perfectly fine, but it loads all modules even if they are not used.
import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
// Require in a base component context
const requireComponent = require.context(
'../components/base', false, /base-[\w-]+\.vue$/,
)
requireComponent.keys().forEach(fileName => {
// Get component config
const componentConfig = requireComponent(fileName)
// Get PascalCase name of component
const componentName = upperFirst(
camelCase(fileName.replace(/^\.\//,
'').replace(/\.\w+$/,
'')),
)
// Register component globally
Vue.component(componentName, componentConfig.default || componentConfig)
})
What I tried to achieve was to create async components instead. Like so
import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
// Require in a base component context
const requireComponent = require.context(
'../components/base', false, /base-[\w-]+\.vue$/,
)
requireComponent.keys().forEach(fileName => {
const componentPath = fileName.replace('./', '../components/base/');
// Get PascalCase name of component
const componentName = upperFirst(
camelCase(fileName.replace(/^\.\//,
'').replace(/\.\w+$/,
'')),
)
// Register component globally
Vue.component(componentName, () => import(componentPath))
})
If the case of the code above vue throws an error
vue.esm.js:591 [Vue warn]: Failed to resolve async component: function () {
return __webpack_require__("./lib lazy recursive")(componentPath);
}
Reason: Error: Cannot find module '../components/base/base-button.vue'
If I manually write down Vue.component('BaseButton', () => import('../components/base/base-button.vue'))
it works without problem but when I try to do that dynamically it fails. Is it possible to do such async component registration if so how?
This doesn't work either:
const button = '../components/base/base-button.vue'
Vue.component('BaseButton', () => import(button))
only if I literally right the string into import function.
import cannot be used when the module path is fully dynamic. See the docs:
Fully dynamic statements, such as import(foo), will fail because webpack requires at least some file location information. This is because foo could potentially be any path to any file in your system or project. The import() must contain at least some information about where the module is located, so bundling can be limited to a specific directory or set of files.
You didn't specify the mode argument for require.context which defaults to "sync"; this means all modules matched will be loaded straight away. You want to use "lazy" which generates a lazy-loadable chunk for each module.
Untested, but I imagine it'll be something like this:
const context = require.context('../components/base', false, /base-[\w-]+\.vue$/, 'lazy');
context.keys().forEach(fileName => {
const componentPath = fileName.replace('./', '../components/base/');
// Get PascalCase name of component
const componentName = upperFirst(
camelCase(fileName.replace(/^\.\//,
'').replace(/\.\w+$/,
'')),
);
// Register component globally
Vue.component(componentName, () => context(fileName));
});
Related
Trying to create an xterm react component in Next.js I got stuck as I'm not able to get over an error message I've never got before.
I'm trying to import a npm client-side module called xterm, but if I add the import line the application crashes.
import { Terminal } from 'xterm'
The error reads Server Error... ReferenceError: self is not defined
and then shows this chunk of code as Source
module.exports = require("xterm");
According to some research I did, this has to do with Webpack and could be helped if something like this was done:
output: {
globalObject: 'this'
}
Would you know how to fix this?
The error occurs because the library requires Web APIs to work, which are not available when Next.js pre-renders the page on the server-side.
In your case, xterm tries to access the window object which is not present on the server. To fix it, you have to dynamically import xterm so it only gets loaded on the client-side.
There are a couple of ways to achieve this in Next.js.
#1 Using dynamic import()
Move the import to your component's useEffect, then dynamically import the library and add your logic there.
useEffect(() => {
const initTerminal = async () => {
const { Terminal } = await import('xterm')
const term = new Terminal()
// Add logic with `term`
}
initTerminal()
}, [])
#2 Using next/dynamic with ssr: false
Create a component where you add the xterm logic.
// components/terminal-component
import { Terminal } from 'xterm'
function TerminalComponent() {
const term = new Terminal()
// Add logic around `term`
return <></>
}
export default TerminalComponent
Then dynamically import that component when using it.
import dynamic from 'next/dynamic'
const TerminalComponent = dynamic(() => import('<path-to>/components/terminal-component'), {
ssr: false
})
As an alternative, you could add the logic directly when dynamically importing the library with next/dynamic to avoid having an extra file for it.
import dynamic from 'next/dynamic'
const Terminal = dynamic(
{
loader: () => import('xterm').then((mod) => mod.Terminal),
render: (props, Terminal) => {
const term = new Terminal()
// Add logic with `term`
return <></>
}
},
{
ssr: false
}
)
Trying out Next.js but I'm struggling with the following. Just tried to install react-hook-mousetrap and imported it like I normally would:
import useMousetrap from "react-hook-mousetrap";
This gives me the following error:
SyntaxError: Cannot use import statement outside a module
1 > module.exports = require("react-hook-mousetrap");
I am not sure what this means? I then thought it might be a problem with Nextjs's SSR, since my library enables hotkeys and will use some browser APIs. If you already know that I am on the wrong track here you can stop reading now.
What I did next however was this, I tried dynamic imports:
1. Dynamic import with next/dynamic
First thing I came across was next/dynamic, but this seems to be for JSX / React Components only (correct me if I'm wrong). Here I will be importing and using a React hook.
2. Dynamic import with await (...).default
So I tried dynamically importing it as a module, but I'm not sure how to do this exactly.
I need to use my hook at the top level of my component, can't make that Component async and now don't know what to do?
const MyComponent = () => {
// (1) TRIED THIS:
const useMousetrap = await import("react-hook-mousetrap").default;
//can't use the hook here since my Component is not async; Can't make the Component async, since this breaks stuff
// (2) TRIED THIS:
(async () => {
const useMousetrap = (await import("react-hook-mousetrap")).default;
// in this async function i can't use the hook, because it needs to be called at the top level.
})()
//....
}
Any advice here would be appreciated!
The error occurs because react-hook-mousetrap is exported as an ESM library. You can have Next.js transpile it using next-transpile-modules in your next.config.js.
const withTM = require('next-transpile-modules')(['react-hook-mousetrap']);
module.exports = withTM({ /* Your Next.js config */});
I don't know if my answer is actual, but i'm facing whith this problem today, and what that i done:
//test component for modal
const Button: React.FC<{close?: () => void}> = ({ close }) => (
<React.Fragment>
<button type="button" onClick={ close }>Close</button>
</React.Fragment>
);
// async call import react custom hook in next js whithout a dynamic
//import
let newHook;
(async () => {
const { hookFromNodeModules } =
await import('path/to/hook');
newHook = hookFromNodeModules;
})();
export default function Home() {
// check if hook is available
const openModal = newHook && newHook();
const { t } = useTranslation('common');
// useCallback for update call function when hook is available
const handleOpen = React.useCallback(() => {
openModal?.openModal(Button, {});
}, [openModal]);
return ( ...your code )
}
hope this help!)
screen from next.js app
Our Webpack bundle contains placeholders for the dynamic import of icons. An example dynamic import is as follows:
const { icon: iconName } = this.props;
const faIconName = `fa${iconName.replace(/./, c => c.toUpperCase())}`;
import(
/* webpackInclude: /\.js$/ */
`#fortawesome/pro-light-svg-icons/${faIconName}`
).then(faIcon => {
if (this.mounted) {
this.setState({ faIcon });
}
});
We decided for this strategy in order to prevent Webpack from bundling up the whole collection of FontAwesome icons.
Most recently we've realised the need to have internal builds where the dynamic import does not occur and pay the price of the larger bundle. The following code has been placed in our icon code (alongside the dynamic import above):
const faIconName = `fa${iconName.replace(/./, c => c.toUpperCase())}`;
let faIcon;
try {
faIcon = require(`#fortawesome/pro-light-svg-icons/${faIconName}.js`)[faIconName];
} catch (e) {}
Both loading strategies work fine when used one at a time. The issue comes when they coexist in the icon component.
I have verified that the import instruction leads Webpack to create in the bundle what to me seems a synthetic JS file generated with the command:
webpack:/// ./node_modules/#fortawesome/pro-light-svg-icons lazy ^\.\/.*$ include: \.js$ namespace object
When both import and require instructions are present in the Icon component, the synthetic file is different from when the sole import is encountered.
In detail, the object called map in the synthetic file contains values that are arrays with 3 elements in the import case and with 2 elements in the import+require case; the synthetic code tries to access the third element and everything crashes.
Can anyone comment on this issue?
I found an answer, you may check my full answer here
To make long story short i imported basing on the list and put all the imported components to Component's state. Afterwards i've created the React.createElememt's from the stored imported components and pulled all of them to Render
componentDidMount = () => {
//we get elements list from any source to redux-store
this.props.getForms();
//access redux-store to the list
const forms = this.props.configBody.sets;
//make deep object copy
const updatedState = { ...this.state };
updatedState.modules = [];
if (forms) {
//here is the very dynamic import magic: we map the import list and prepare to store the imports in Component`s state
const importPromises = forms.map(p =>
import(`../TemplateOrders/Template${p.order}`)
.then(module => {
updatedState.modules.push(module.default)
})
.catch(errorHandler(p))
)
//wait till all imports are getting resolved
Promise.all(importPromises)
.then(res =>
//then run setState
this.setState({ ...updatedState }, () => {
console.log(this.state);
}))
}
}
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
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