I have some img tag which I fill it with dynamic address with require, it works as expected in the component but when I write a test for it throws this error
console.error
Error: Configuration error:
Could not locate module ~/assets/images/flags/undefined.png mapped as:
/home/user/Desktop/Workspace/porject/$1.
Please check your configuration for these entries:
{
"moduleNameMapper": {
"/^~\/(.*)$/": "/home/user/Desktop/Workspace/porject/$1"
},
"resolver": undefined
}
at createNoMappedModuleFoundError (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:579:17)
at Resolver.resolveStubModuleName (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:541:19)
at Resolver.getMockModule (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:380:31)
at Resolver._isModuleResolved (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:477:42)
at Resolver._getAbsolutePath (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:455:17)
at Resolver.getModuleID (/home/user/Desktop/Workspace/porject/node_modules/jest-resolve/build/resolver.js:424:31)
at Runtime._shouldMock (/home/user/Desktop/Workspace/porject/node_modules/jest-runtime/build/index.js:1917:37)
at Runtime.requireModuleOrMock (/home/user/Desktop/Workspace/porject/node_modules/jest-runtime/build/index.js:1204:14)
at Proxy.render (/home/user/Desktop/Workspace/porject/components/newComponents/global/ChangeLanguage/index.vue:2903:14)
at /home/user/Desktop/Workspace/porject/node_modules/#vue/composition-api/dist/vue-composition-api.common.js:1891:35
at logError (node_modules/vue/dist/vue.common.dev.js:1902:13)
at globalHandleError (node_modules/vue/dist/vue.common.dev.js:1893:3)
at handleError (node_modules/vue/dist/vue.common.dev.js:1853:5)
at VueComponent.Vue._render (node_modules/vue/dist/vue.common.dev.js:3570:7)
at VueComponent.updateComponent (node_modules/vue/dist/vue.common.dev.js:4078:21)
at Watcher.get (node_modules/vue/dist/vue.common.dev.js:4490:25)
at Watcher.run (node_modules/vue/dist/vue.common.dev.js:4565:22)
here is a test file:
import { createLocalVue, shallowMount } from '#vue/test-utils'
import Vuex from 'vuex'
import { $axios } from '~/test/unit/__mocks__/util'
import storeConfig from '~/test/unit/__mocks__/store'
import ChangeLanguage from '~/components/global/ChangeLanguage/index.vue'
const localVue = createLocalVue()
localVue.use(Vuex)
// eslint-disable-next-line import/no-named-as-default-member
const store = new Vuex.Store({
modules: {
index: {
state: storeConfig().modules.index.state,
getters: storeConfig().modules.index.getters,
mutations: storeConfig().modules.index.mutations,
actions: storeConfig().modules.index.actions,
namespaced: false,
},
},
})
describe('global/changeLanguage.vue', () => {
beforeEach(() => {
console.error = jest.fn()
})
const wrapper = shallowMount(ChangeLanguage, {
store,
localVue,
props: {
visibility: { default: false },
},
mocks: {
$axios,
},
})
test('checks if visibility changes and event emit', async () => {
await wrapper.setData({ isLanguagesVisible: true })
await wrapper.find('[data-test="change-visibility"]').trigger('click')
expect(wrapper.emitted()).toHaveProperty('changeVisibility')
})
})
and here is the component codes:
<template>
<div>
<img
:src="require(`~/assets/images/flags/${selectedLanguage.flagCode}.png`)"
:alt="selectedLanguage.name"
class="rounded-md w-8 h-6"
/>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "#nuxtjs/composition-api";
import { Language } from "~/types/components/layouts";
export default defineComponent({
setup() {
const selectedLanguage = ref<Language>({
code: "en",
name: "English",
link: "/",
flagCode: "us",
});
return {
selectedLanguage,
};
},
});
</script>
and here is the jest.config.js file:
module.exports = {
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/$1',
'^~/(.*)$': '<rootDir>/$1',
'/^components/(.*)$/': '<rootDir>/components/$1',
'^vue$': 'vue/dist/vue.common.js',
},
moduleFileExtensions: ['ts', 'js', 'vue', 'json'],
transform: {
'^.+\\.ts$': 'ts-jest',
'^.+\\.js$': 'babel-jest',
'.*\\.(vue)$': 'vue-jest',
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/test/unit/fileTransformer.js',
},
collectCoverage: true,
collectCoverageFrom: [
'<rootDir>/components/**/*.vue',
'<rootDir>/pages/**/*.vue',
],
testEnvironment: 'jsdom',
setupFiles: ['<rootDir>/test/unit/setup.js'],
}
and setup.js file:
import Vue from 'vue'
import { config } from '#vue/test-utils'
import * as CompositionApi from '#nuxtjs/composition-api'
Vue.use(CompositionApi)
Vue.config.silent = true
// Mock some of global components
config.stubs['nuxt-link'] = true
config.stubs['client-only'] = true
config.stubs.fa = true
// Mock some of global methods
config.mocks.$t = (i) => i
config.mocks.t = (i) => i
config.mocks.localePath = (i) => i
config.mocks.switchLocalePath = (i) => i
and fileTransformer.js file:
const path = require('path');
module.exports = {
process(src, filename, config, options) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
},
};
and package.json file
{
"name": "project",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate",
"lint:js": "eslint --ext \".js,.vue\" --ignore-path .gitignore .",
"lint": "npm run lint:js",
"test": "jest --watch"
},
"dependencies": {
"#fortawesome/free-brands-svg-icons": "^5.15.4",
"#fortawesome/free-solid-svg-icons": "^5.15.4",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/composition-api": "^0.30.0",
"#nuxtjs/i18n": "^7.0.3",
"#nuxtjs/pwa": "^3.3.5",
"cookie-universal-nuxt": "^2.1.5",
"core-js": "^3.15.1",
"gsap": "^3.8.0",
"nuxt": "^2.15.7",
"nuxt-fontawesome": "^0.4.0",
"vue": "^2.6.14",
},
"devDependencies": {
"#babel/eslint-parser": "^7.14.7",
"#nuxt/types": "^2.15.7",
"#nuxt/typescript-build": "^2.1.0",
"#nuxtjs/eslint-config-typescript": "^6.0.1",
"#nuxtjs/eslint-module": "^3.0.2",
"#nuxtjs/tailwindcss": "^4.2.0",
"#types/jest": "^27.0.2",
"#vue/test-utils": "^1.2.1",
"babel-core": "7.0.0-bridge.0",
"babel-jest": "^27.0.5",
"eslint": "^7.29.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-nuxt": "^2.0.0",
"eslint-plugin-vue": "^7.12.1",
"fibers": "^5.0.0",
"jest": "^27.0.5",
"postcss": "^8.3.5",
"prettier": "^2.3.2",
"sass": "^1.42.1",
"sass-loader": "^10.2.0",
"ts-jest": "^27.0.3",
"vue-jest": "^3.0.4",
"vuex": "^3.6.2"
}
}
I'm using nuxt 2 with typescript and composition API
how can i fix this?
Problem solved with ternary if:
<img
:src="
selectedLanguage.flagCode
? require(`~/assets/images/flags/${selectedLanguage.flagCode}.png`)
: ''
"
class="rounded-md w-8 h-6"
/>
Related
My Application with MUI in DEV has one custom design
My Application with MUI in Prod has no custom design
Should I make something different?
Is missing some extra configuration?
Sample of something that is not working:
<Typography className={styles.customStyle} component="h1">
{t("Translation")}
</Typography>
The className={styles.customStyle} is totally ignored in Prod
This works fine in DEV.
My configuration
node v19.0.0
Package.json
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"#emotion/react": "^11.10.5",
"#emotion/styled": "^11.10.5",
"#mui/icons-material": "^5.11.0",
"#mui/material": "^5.11.0",
"#mui/styles": "^5.11.1",
"#next/font": "13.0.7",
"#types/node": "^18.13.0",
"#types/react": "18.0.26",
"#types/react-dom": "18.0.9",
"axios": "^1.2.1",
"country-flag-icons": "^1.5.5",
"eslint": "8.29.0",
"eslint-config-next": "^13.1.1",
"html-entities": "^2.3.3",
"i18next": "^22.4.6",
"json5": "^1.0.2",
"next": "^13.1.1",
"next-translate": "^1.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-i18next": "^12.1.1",
"sass": "^1.57.0",
"typescript": "4.9.4"
}
}
next.config.js
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
experimental: {
appDir: true,
},
}
module.exports = nextConfig
FIXED:
After reading this article: https://blog.logrocket.com/getting-started-with-mui-and-next-js/
I saw that it was missing added <CacheProvider />.
So after that, the style custom works fine.
SOLUTION:
First, create a new file in the utils directory called createEmotionCache.js.
import createCache from "#emotion/cache";
export default function createEmotionCache() {
return createCache({ key: "css", prepend: true });
}
After go to the _app.js or page.js (if using LAYOUT RFC)
....
import { CacheProvider } from "#emotion/react";
const clientSideEmotionCache = createEmotionCache();
function MyApp({
Component,
emotionCache = clientSideEmotionCache,
pageProps,
}) {
return (
<CacheProvider value={emotionCache}>
<App />
</CacheProvider>
);
}
export default MyApp;
Thanks it.
React 16.8 | Typescript 3.5
I want to run useEffect to update an array inside App() every time a QR scanner inside a node module imported to the app updates one of its fields.
Alternatively, I would like to receive the data from 'onScan'.
How do you import and use as a dep elements of node module components? There's a page within a file called 'SendPage.jsx' which runs a useState hook called 'setTo()' to update a value 'to'. I'm looking to intercept that 'to' value and use it inside App().
These are my dependencies in node modules. Specifically, inside the "#burner-wallet/modern-ui" there's
"#burner-wallet/assets": "^1.0.0",
"#burner-wallet/core": "^1.0.0",
"#burner-wallet/exchange": "^1.0.0",
"#burner-wallet/modern-ui": "^1.0.9",
"#types/node": "12.0.4",
"#types/react": "*",
"#types/react-dom": "16.8.4",
"#types/react-router-dom": "^4.3.3",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "^3.2.0",
"typescript": "3.5.1",
"universal-cookie": "^4.0.4"
},
This is the package.json inside the "#burner-wallet/modern-ui" module space:
"name": "#burner-wallet/modern-ui",
"version": "1.0.9",
"license": "MIT",
"main": "dist/ModernUI.js",
"types": "dist/ModernUI.d.ts",
"scripts": {
"build": "tsc",
"start-local": "tsc -w",
"start-basic": "tsc -w"
},
"devDependencies": {
"#babel/plugin-proposal-class-properties": "^7.4.4",
"#babel/plugin-proposal-object-rest-spread": "^7.4.4",
"#babel/preset-typescript": "^7.3.3"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/"
},
"repository": {
"type": "git",
"url": "https://github.com/burner-wallet/burner-wallet-2.git",
"directory": "packages/modern-ui"
},
"dependencies": {
"#burner-wallet/types": "^1.0.2",
"#burner-wallet/ui-core": "^1.0.2",
"#types/clipboard": "^2.0.1",
"#types/color": "^3.0.0",
"#types/ethereumjs-util": "^5.2.0",
"#types/qrcode.react": "^0.8.2",
"#types/react": "*",
"#types/react-qr-reader": "^2.1.2",
"#types/react-router-dom": "^4.3.4",
"#types/styled-components": "4.1.8",
"clipboard": "^2.0.4",
"color": "^3.1.2",
"ethereumjs-util": "^6.1.0",
"qrcode.react": "^0.9.3",
"react-qr-reader": "^2.2.1",
"styled-components": "^5.0.1"
}
}
My app.tsx file:
import React, { useContext, useEffect, useState } from 'react';
import styled from 'styled-components';
import ScanContext from './scancontext';
import { setLocally, getLocallyStoredQRs } from './localstorage';
// import { xdai, dai, eth } from '#burner-wallet/assets';
import { xdai} from '#burner-wallet/assets';
import BurnerCore, { HistoryEvent } from '#burner-wallet/core';
import { InjectedSigner, LocalSigner } from '#burner-wallet/core/signers';
import { InfuraGateway, InjectedGateway, XDaiGateway, } from '#burner-wallet/core/gateways';
import Exchange, { Uniswap, XDaiBridge } from '#burner-wallet/exchange';
import ModernUI from '#burner-wallet/modern-ui';
import { HistoryProps } from '#burner-wallet/core/History';
const core = new BurnerCore({
signers: [new InjectedSigner(), new LocalSigner()],
gateways: [
new InjectedGateway(),
new InfuraGateway(process.env.REACT_APP_INFURA_KEY),
new XDaiGateway(),
],
// TODO use Sai
// assets: [xdai, dai, eth],
assets: [xdai],
});
const exchange = new Exchange({
pairs: [new XDaiBridge(), new Uniswap('dai')],
});
const QRCardsSpace = styled.div`
padding-bottom: 100px;
`;
function App() {
const [newQRs, setQR] = useState('');
// const storedCookieQRs: string[] = getLocallyStoredQRs();
const appUI = <ModernUI
title="Vincenz Burner Wallet"
core={core}
plugins={[exchange]}
/>
useEffect(() => {
// This will be where the addresses are assigned when read
console.log("useEffect");
console.log("newQRs" , newQRs);
var latestToAddress = "0x4f0f4m";
const QRData = [latestToAddress];
setQR(latestToAddress);
setLocally(QRData);
}, [appUI]); // Set here the conditional change to the QR data
return (
<div>
{appUI}
<QRCardsSpace>
<ScanContext />
</QRCardsSpace>
</div>
) };
export default App;
I am using material-ui theme along with redux-toolit in gatsby.
My theme.ts file:
import { createMuiTheme } from "#material-ui/core";
import { useSelector } from "react-redux";
import { State } from "./Types/SliceTypes";
export const Theme = () => {
const islit = useSelector((state: State) => state.themes.value);
const theme = createMuiTheme({
palette: {
type: islit ? "light" : "dark",
},
});
return theme;
}
Now When I import this Theme in gatsby-browser and gatsby-ssr file it give an error. Invalid hook call. Hooks can only be called inside of the body of a function component
Even if I don't use islit and use theme only that is inside the Theme function the code still doesn't work.
My gatsby-browser.js and gatsby-ssr.js file:
import React from 'react';
import { Provider } from 'react-redux';
import store from './src/Global/store';
import { ThemeProvider } from "#material-ui/core/styles";
import { Theme } from "./src/Global/theme";
export const wrapRootElement = ({ element }) => {
return <Provider store={store}><ThemeProvider theme={Theme()}>{element}</ThemeProvider></Provider>;
};
My gatsby-config.js file:
plugins: [
`gatsby-plugin-react-helmet`,
`gatsby-plugin-material-ui`,
`gatsby-plugin-image`,
My package.json file:
{
"name": "gatsby-starter-default",
"private": true,
"description": "A simple starter to get up and developing quickly with Gatsby",
"version": "0.1.0",
"author": "Kyle Mathews <mathews.kyle#gmail.com>",
"dependencies": {
"#contentful/rich-text-react-renderer": "^14.1.3",
"#material-ui/core": "^4.11.3",
"#material-ui/icons": "^4.11.2",
"#reduxjs/toolkit": "^1.5.1",
"#types/react": "^17.0.3",
"#types/react-dom": "^17.0.3",
"#types/react-redux": "^7.1.16",
"#typescript-eslint/eslint-plugin": "^4.22.0",
"#typescript-eslint/parser": "^4.22.0",
"dotenv": "^8.2.0",
"firebase": "^8.4.1",
"firebaseui": "^4.8.0",
"gatsby": "^3.3.0",
"gatsby-plugin-firebase": "^0.2.0-beta.4",
"gatsby-plugin-gatsby-cloud": "^2.2.0",
"gatsby-plugin-image": "^1.2.1",
"gatsby-plugin-manifest": "^3.2.0",
"gatsby-plugin-material-ui": "^3.0.1",
"gatsby-plugin-offline": "^4.2.0",
"gatsby-plugin-react-helmet": "^4.2.0",
"gatsby-plugin-sharp": "^3.2.1",
"gatsby-source-contentful": "^5.3.0",
"gatsby-source-filesystem": "^3.2.0",
"gatsby-transformer-remark": "^4.0.0",
"gatsby-transformer-sharp": "^3.2.0",
"prop-types": "^15.7.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-helmet": "^6.1.0",
"react-redux": "^7.2.3",
"typescript": "^4.2.4"
},
"devDependencies": {
"#types/react-helmet": "^6.1.1",
"prettier": "2.2.1"
},
"keywords": [
"gatsby"
],
"license": "0BSD",
"scripts": {
"build": "gatsby build",
"develop": "gatsby develop",
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,md}\"",
"start": "npm run develop",
"serve": "gatsby serve",
"clean": "gatsby clean",
"test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://github.com/gatsbyjs/gatsby-starter-default"
},
"bugs": {
"url": "https://github.com/gatsbyjs/gatsby/issues"
}
}
I have a similar set up and was able to solve this by following this setup recommended by MUI; https://github.com/mui-org/material-ui/tree/next/examples/gatsby
In the file gatsby/plugins/gatsby-plugin-top-layout/TopLayout.js you can add your redux Provider;
import { Provider } from "react-redux";
import { ThemeProvider } from "#material-ui/core/styles";
import { Theme } from "../../src/Global/theme";
import store from '../../src/Global/store';
...
<Provider store={store}>
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
{props.children}
</ThemeProvider>
</Provider>
...
For a new project, I started using rollup to bundle a UI library and consume that library in a react application. I'm also using yarn workspaces for the internal dependency management between the UI library and the web app.
When I try to use the UI library in my web app, the import returns undefined and throws the "cannot get from undefined" error.
TypeError: Cannot read property 'NavBar' of undefined
[0] at App (C:/Users/user/dev/project/packages/project-web/src/pages/App.jsx:9:6)
The webapp code:
import React from 'react';
import {NavBar} from 'project-ui';
const App = () => (
<div>
<NavBar/>
<div>App component!x</div>
</div>
);
root package.json:
{
"name": "project",
"version": "1.0.0",
"private": true,
"workspaces": [
"packages/*"
]
}
UI package.json:
{
"name": "project-ui",
"version": "1.0.0",
"main": "dist/project-ui.cjs.js",
"jsnext:main": "dist/project-ui.es.js",
"module": "dist/project-ui.es.js",
"files": ["dist"],
"scripts": {
"build": "rollup -c"
},
"peerDependencies": {
"react": "16.3.2",
"react-dom": "16.3.2"
},
"devDependencies": {
"babel-core": "6.26.3",
"babel-plugin-external-helpers": "6.22.0",
"babel-preset-env": "1.6.1",
"babel-preset-react": "6.24.1",
"babel-preset-stage-2": "6.24.1",
"rollup": "0.60.0",
"rollup-plugin-babel": "3.0.4",
"rollup-plugin-commonjs": "9.1.3",
"rollup-plugin-node-resolve": "3.0.0",
"rollup-plugin-replace": "2.0.0",
"rollup-plugin-uglify": "4.0.0"
}
}
web app package.json:
{
"name": "project-web",
"version": "1.0.0",
"scripts": {
"build": "webpack --colors --display-error-details --config=webpack/webpack.dev.js",
"dev": "concurrently --kill-others \"npm run dev:start\"",
"dev:start": "node ./server/index.js"
},
"dependencies": {
"babel-polyfill": "^6.26.0",
"express": "^4.16.3",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"project-ui": "1.0.0"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-eslint": "^8.2.3",
"babel-loader": "^7.1.4",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-dynamic-import-node": "^1.2.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"concurrently": "^3.5.1",
"eslint": "^4.19.1",
"eslint-loader": "^2.0.0",
"eslint-plugin-react": "^7.7.0",
"piping": "^1.0.0-rc.4",
"webpack": "^4.6.0",
"webpack-cli": "^2.0.15",
"webpack-dev-middleware": "^3.1.3",
"webpack-dev-server": "^3.1.3",
"webpack-hot-middleware": "^2.22.1",
"webpack-node-externals": "^1.7.2"
}
}
rollup config:
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import replace from 'rollup-plugin-replace';
import { uglify } from 'rollup-plugin-uglify';
import pkg from './package.json'
const FORMATS = {
UMD: 'umd',
ES: 'es',
CJS: 'cjs'
};
const allowedFormats = [FORMATS.UMD, FORMATS.ES, FORMATS.CJS];
const bundle = (fileFormat, {format, minify}) => {
if (!allowedFormats.includes(format)) {
throw new Error(`Invalid format given: ${format}`);
}
const shouldMinify = minify && format === FORMATS.UMD;
const externals = format === FORMATS.UMD
? Object.keys(pkg.peerDependencies || {})
: [
...Object.keys(pkg.dependencies || {}),
...Object.keys(pkg.peerDependencies || {})
];
return {
input: 'src/index.js',
output: {
file: fileFormat.replace('{format}', shouldMinify ? `${format}.min` : format),
format,
name: 'project-ui',
exports: 'named',
globals: {
react: 'React',
'prop-types': 'PropTypes'
}
},
external: externals,
plugins: [
resolve({ jsnext: true, main: true }),
commonjs({ include: 'node_modules/**' }),
babel({
exclude: 'node_modules/**',
}),
format === FORMATS.UMD
? replace({'process.env.NODE_ENV': JSON.stringify(shouldMinify ? 'production' : 'development')})
: null,
shouldMinify ? uglify() : null
].filter(Boolean)
};
};
export default [
bundle('dist/project-ui.{format}.js', {format: FORMATS.UMD, minify: true}),
bundle('dist/project-ui.{format}.js', {format: FORMATS.CJS}),
bundle('dist/project-ui.{format}.js', {format: FORMATS.ES})
];
the actual generated code from rollup:
import React from 'react';
var NavBar = function NavBar() {
return React.createElement(
'header',
null,
'nav bar'
);
};
module.exports = exports['default'];
export { NavBar };
The original navbar:
import React from 'react';
const NavBar = () => (
<header>
nav bar
</header>
);
export default NavBar;
index.js:
export { default as NavBar} from './NavBar/NavBar';
.babelrc:
{
"presets": [
["env", {
"loose": true,
"modules": false,
"targets": {
"browsers": ["last 2 versions"]
}
}],
"react",
"stage-2"
],
"plugins": [
"transform-runtime",
"add-module-exports",
"external-helpers"
]
}
The generated rollup code looks to be ok, so I'm thinking this is a yarn issue, but I'm not sure. Any help would be appreciated!
Regards
Cornel
The problem must be in the way you are transpilling the code with babel/rollup. I have a live example in how your code should look in an online babel:
The generated code for me is:
import React from 'react';
const NavBar = () => React.createElement(
'header',
null,
'nav bar'
);
export default NavBar; // first define default and then we assign export['default']
module.exports = exports['default'];
Observe that in this code we first assign export default to the desired value and then we assign export['defaults'] (when I debug your example I get that export['default'] is undefined, hence you get the error Cannot read property 'NavBar' of undefined [0], since you are passing undefined to exports.
This is done by the plugin 'add-module-exports', that is kind of necessary if you really need module.exports (that shouldnt be needed unless NodeJS or some RequireJS is present).
In order to make it work, just remove "add-module-exports" from your plugins in the project-ui .babelrc.
I've been trying to setup VueJS2 with Grunt & Browserify only to keep hitting the same error of the template or render function not being defined: [Vue warn]: Failed to mount component: template or render function not defined.
Here's the code:
Index.js:
import Vue from 'vue';
import Router from 'vue-router';
import App from './components/App.vue'
import Resource from 'vue-resource'
import indexComponent from './components/index/template.vue'
Vue.use(Router)
Vue.use(Resource)
// route config
let routes = [
{
path: '/',
name: 'home',
component: indexComponent
},
{ path: '*', redirect: '/' }
]
// Set up a new router
let router = new Router({
routes: routes
})
// Start up our app
new Vue({
router: router,
render: h => h(App)
}).$mount('#app')
gruntfile.js:
browserify: {
js: {
files: {
'src/assets/js/app.js': 'src/js/index.js'
},
options: {
debug: true,
bundleDelay: 1000,
transform: [ ["vueify"], ["babelify"] ]
}
}
},
Package.json:
{
"name": "testing",
"version": "0.1.0",
"description": "test",
"main": "src/index.js",
"license": "ISC",
"scripts": {
"test": "grunt test"
},
"browserify": {
"transform": [
"babelify",
"vueify"
]
},
"browser": {
"vue": "vue/dist/vue.common.js"
},
"devDependencies": {
"babel-core": "^6.0.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-es2015": "^6.0.0",
"babelify": "^6.0.0",
"browserify": "^14.3.0",
"grunt": "^0.4.5",
"grunt-browserify": "^5.0.0",
"grunt-cli": "^1.2.0",
"grunt-contrib-connect": "^1.0.2",
"grunt-contrib-copy": "^1.0.0",
"grunt-contrib-uglify": "^2.0.0",
"grunt-contrib-watch": "^0.6.1",
"grunt-sass": "^1.2.1",
"partialify": "^3.1.5",
"vue": "^2.3.3",
"vue-resource": "^1.3.4",
"vue-router": "^2.5.3",
"vueify": "^9.4.1"
}
}
Any help would be appreciated.
If you import Vue from 'vue'; you'll get the runtime only build that cannot compile templates, you need the standalone build.
this error arrives when in the system cannot find the template(HTML section of SPA) of .vue file,
in this case it may be App.vue or template.vue.
The file must be in the format of:
`<template>
</template>
<script>
export default{}
</script>
<style>
</style>`