Alternative for "component: () => import()" in VueJS routing - javascript

I downloaded a template online to better understand VueJS and also create a web app. However I have a problem with routing. There is a function in my router's index.js that imports a path. The import syntax seems to be buggy due to some webpack issues. I tried a lot of different things but couldn't fix the bug so I want to find a workaround for that import syntax
This is my code for router's index.js
import Vue from 'vue'
import VueAnalytics from 'vue-analytics'
import Router from 'vue-router'
import Meta from 'vue-meta'
// Routes
import paths from './paths'
// import views from './views'
function route (path, view, name) {
return {
name: name || view,
path,
component: () => import(
`../views/${view}.vue`
)
}
}
Vue.use(Router)
// Create a new router
const router = new Router({
mode: 'history',
routes: paths.map(path => route(path.path, path.view, path.name)).concat([
{ path: '*', redirect: '/home' }
]),
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
}
if (to.hash) {
return { selector: to.hash }
}
return { x: 0, y: 0 }
}
})
Vue.use(Meta)
// Bootstrap Analytics
// Set in .env
// https://github.com/MatteoGabriele/vue-analytics
if (process.env.GOOGLE_ANALYTICS) {
Vue.use(VueAnalytics, {
id: process.env.GOOGLE_ANALYTICS,
router,
autoTracking: {
page: process.env.NODE_ENV !== 'development'
}
})
}
export default router
When i try to build it, I get an error saying:
ERROR in ./src/router/index.js
Module build failed: SyntaxError: C:/djangoProjects/martin - Copy/martin/src/router/index.js: Unexpected token (15:21)
The syntax error is on line (15:21), in the route function on the component: () => import( line and exactly on import. Fixing this issue is a pain so I was wondering if there is a workaround for it without using the import syntax?

If I remember correctly you'll need a plugin for babel that can handle dynamic imports.
Check out:
https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import
Run npm install #babel/plugin-syntax-dynamic-import
Create or open .babelrc
{
"plugins": ["#babel/plugin-syntax-dynamic-import"]
}

Related

export import browser complaint cannot find module

This Meteor app has a template event that maks a Meteor.call, and is causing browser error Cannot find module 'server/plateCheck.js'. The file responsible is:
//app/imports/api/vehicles/methods.js
import { Meteor } from 'meteor/meteor'
import { Vehicles } from './vehicles.js'
import { plateCheck } from "../server/plateCheck.js"; //<<<<<<<<<<
Meteor.methods({
'extractPlateData': function (plate) {
console.log('method called: ', plate)
plateCheck(plate)
}
)},
//app/imports/api/vehicles/server/plateCheck.js
import {Vehicles} from '../imports/api/vehicles/vehicles.js'
const plateCheck = async (plateNumber) => {...}
module.exports = plateCheck;
meteor list includes ecmascript 0.15.1
Why is this and isn't the export/import correct as stated? How to get read of the error? Thanks.
Your relative path is wrong. The server folder is in the same directory as methods.js, so you'll need to import
import { plateCheck } from "./server/plateCheck.js";
Or you can make all imports absolute:
//app/imports/api/vehicles/methods.js
import { plateCheck } from "/imports/api/server/plateCheck.js";
...
//app/imports/api/vehicles/server/plateCheck.js
import {Vehicles} from '/imports/api/vehicles/vehicles.js'

Unexpected undefined while import with Webpack

I have a problem that has never happened to me before: I'm compiling a little basic starter browser web app (with React) using Webpack + Babel 7.
I've got three different file:
withAuth.js The Auth High Order Component
NavBar.js The NavBar Component
Login.js The Login Form
If I import the withAuth HOC in the NavBar is everything alright, but if I import the withAuth component in the Login.js file it return undefined
/** withAuth.js */
console.log('withAuth Loaded');
const withAuth = Child => ChildProps => (
<AuthContext.Consumer>
{ authClient => <Child {...ChildProps} authClient={authClient} }
</AuthContext.Consumer>
)
export { withAuth };
/** NavBar.js */
import { withAuth } from 'HOC/Auth';
console.log('NavBar Loaded', withAuth); // <- My HOC
const NavBarComponent = (authClient) => { /* ... My Code ... */ }
const NavBar = withAuth(NavBarComponent);
export default NavBar;
/** Login.js */
import { withAuth } from 'HOC/Auth';
console.log('Login Loaded', withAuth); // <- undefined ??
const LoginFormComponent = (authClient) => { /* ... My Code ... */ }
const LoginForm = withAuth(LoginFormComponent);
// /|\
// |
// Will produce an Error, withAuth is Undefined
This is my Webpack Configuration:
/** webpack.config.js */
module.exports = {
entry: { core: 'index.js' },
resolve: {
alias: {
HOC: './path/to/hoc/folder'
}
},
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all'
}
},
plugins: [ /* Various Plugin */ ],
module: {
rules: [ /* My Rules */ ]
}
}
Any one know why my HOC is undefined?
Edit:
I've placed Console Log in the tree file. The result are:
'Login Loaded' - undefined
'withAuth Loaded'
'NavBar Loaded' - function() { }
Edit 2:
This is the files structure:
app/
|-high-order-component/
| |-auth/
| |-withAuth.js
|
|-layout-component/
| |-navbar/
| |-index.js
|
|-pages/
|-auth/
|-login.js
Resolved
After much testing and research throughout the afternoon I came to the solution of the problem. As I said in the question, mine is a larger project and I only partially wrote its structure because I thought the problem was located in those three files.
In reality, the problem was a Circular Dependency problem and not a Webpack configuration problem.
In my project I have a module called 'Route' that store all Path and all Component for Path, so I can build the React Router using Array Map function. That module has a function that allow me to Route through path and that can return me a path string to a Component.
My problem was due to the fact that this module is often called in the project and this has created a Circular Dependency.
Webpack doesn't show the Circular Dependency during compiling, but I found useful adding a plugin, called CircualDependencyPlugin. This plugin will break Webpack compiling when a Circual Dependency will be found.
Splitting the Route module into two files solved my problem.

Jest test: Cannot find module, in typescript component import

The path to my styled objects is correct, however not sure why I'm getting the following error:
Cannot find module '../../shared/models' from 'Astronaut.tsx'
import { moonHoldings } from '../../shared/models';
My simple Jest test:
import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
// #ts-ignore (works with .tsx)
import Astronaut from '../Astronaut.tsx';
describe('<Astronaut /> component', () => {
describe('should render', () => {
const wrapper = shallow(<Astronaut showLogo={true} />);
it ('should render a component matching the snapshot', () => {
const tree = toJson(wrapper);
expect(tree).toMatchSnapshot();
expect(wrapper).toHaveLength(1);
});
});
});
The Astronaut component
import React from 'react';
import { moonHoldings } from '../../shared/models'; // <-- The problem
import { astronaut } from '../../styles'; // <-- This works
const { AstronautContainer, Heading } = astronaut;
interface LogoCheck {
showLogo: boolean;
}
export default (showLogo: LogoCheck) => (
<AstronautContainer>
{ showLogo.showLogo === true ? <Heading>{moonHoldings}</Heading> : null }
<img src="static/astronaut.png" alt="astronaut" />
</AstronautContainer>
);
The Jest config section of my Package.json
"jest": {
"setupTestFrameworkScriptFile": "<rootDir>/jest.setup.js",
"testPathIgnorePatterns": [
"<rootDir>/.next/",
"<rootDir>/node_modules/"
],
"transform": {
"\\.(gql|graphql)$": "jest-transform-graphql",
".*": "babel-jest",
"^.+\\.js?$": "babel-jest"
},
"moduleFileExtensions": [
"js",
"json",
"ts",
"tsx"
],
"modulePaths": [
"<rootDir>/components/",
"<rootDir>/pages/",
"<rootDir>/shared/"
]
}
And my folder structure:
You need to do little configuration for your jest test.
Adding this snippet to your package.json should allow you to take your custom name and map it to your actual folder:
"moduleNameMapper": {
"^#fooBar/(.*)": "<rootDir>/src/barFoo/$1"
},
Ok I just fixed this by created an index file inside of the /shared folder and then exporting out the models that way (Though it should have still worked without the index file):
import { moonHoldings } from '../../shared';
And the index.js:
export { moonHoldings, nomicsLink } from './copy';
In my case, I got this error in a lot of instances inside my test file and the solution was to use file paths based mapping in the moduleNameMapper option inside my jest.config file. This helps us to map our absolute paths with their corresponding relative ones.
For example, if you are getting this error -
● Test suite failed to run
Cannot find module 'jsroot/io' from 'src/some-file.ts'
Adding this should work -
moduleNameMapper: {
// 'absolute-path': 'relative-path'
'jsroot/io': '<rootDir>/node_modules/jsroot/',
},
where <rootDir> is the root of the directory containing your Jest config file or the package.json.

Cannot Import modules from Nuxt.js middleware

I try to import modules from middleware, type error occurs and the Nuxt application does not start.
The code is as follows.
The application uses nuxt-community / starter-template.
nuxt.config.js (jsut add only router on default file)
module.exports = {
router: {
middleware: 'auth'
},
middleware/auth.js
import { Auth } from aws-amplify
export default ( ) => {
const user = Auth.currentUserInfo()
console.log(user)
}
run npm run dev (error occur)
Cannot read property 'indexOf' of undefined
Thanks your help!

jspm cannot find globalResources of a 'feature' plugin for Aurelia app

Aurelia docs describe how setup and use a feature plugin at http://aurelia.io/docs.html#features
I'm having some trouble because it seems that jspm or Aurelia is transforming paths to resources. I discovered that if I specify a current path with .aurelia.use.feature('./plugins/auth'); that calvert-auth/index.js cannot be found when booting. The request looks correct, but the browser throws a 404 error. I fixed that simply by removing the "./" from .aurelia.use.feature('plugins/auth');
Next, I added a call in index.s's configure() to frameworkConfig.globalResources('auth'). This causes a new 404 error because the request is for calvert-auth/auth.html instead of the expected calvert-auth/auth.js
I suspect the problem may be in the jspm config or maybe corejs, but haven't been able to isolate it yet.
How do I create and use internal feature plugins for Aurelia? Here are the classes:
config.js
...
paths: {
"*": "dist/*",
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
...
main.js
import 'bootstrap';
import authConfig from './auth-config';
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.feature('plugins/calvert-auth', (baseConfig) => {
baseConfig.configure(authConfig);
});
aurelia.start().then(a => a.setRoot());
}
plugins/calvert-auth/auth.js
export class Auth {
constructor() {
console.log('Auth: constructor()');
}
}
plugins/calvert-auth/index.js
import {BaseConfig} from './baseConfig';
export function configure(frameworkConfig, configCallback) {
frameworkConfig.globalResources('./auth');
let baseConfig = frameworkConfig.container.get(BaseConfig);
if (configCallback !== undefined && typeof(configCallback) === 'function') {
configCallback(baseConfig);
}
}
Try this:
Assuming your code above, and this structure:
main.js
plugins/calvert-auth/index.js
plugins/calvert-auth/auth.js
In main.js:
import 'bootstrap';
import authConfig from './auth-config';
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.feature('plugins/calvert-auth', (baseConfig) => {
baseConfig.configure(authConfig);
});
aurelia.start().then(a => a.setRoot());
}
In plugins/calvert-auth/index.js:
export function configure(frameworkConfig, configCallback) {
// this assumes you're importing a view model
frameworkConfig.globalResources('auth');
}
In plugins/calvert-auth/auth.js:
import {noView} from 'aurelia-framework';
#noView
export class Auth {
constructor() {
console.log('Auth: constructor()');
}
}

Categories

Resources