I want to use express-routemagic with es6 syntax (import). My approach so far goes like this:
Router.js
import express from "express";
import homepageRouter from "./homepage_router.js";
import usersRouter from "./users_router.js";
const app = express();
app.use('/', homepageRouter);
app.use(process.env.pathUrl, usersRouter);
export default app;
app.js
import magic from 'express-routemagic';
magic.use(app);
I want to note that, so far I've built the application using es5 and it worked fine. When I migrate it to es6, I get the error:
node:internal/process/esm_loader:94
internalBinding('errors').triggerUncaughtException(
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/grigorisbachtsevanos/Documents/EaaS-platform-1/routes/index.js from /Users/grigorisbachtsevanos/Documents/EaaS-platform-1/node_modules/express-routemagic/index.js not supported.
Instead change the require of /Users/grigorisbachtsevanos/Documents/EaaS-platform-1/routes/index.js in /Users/grigorisbachtsevanos/Documents/EaaS-platform-1/node_modules/express-routemagic/index.js to a dynamic import() which is available in all CommonJS modules.'.
I also have added type: module to my package.js. How should I approach this?
Related
In my node.js (express.js) project, I try to wrap axios to create a HttpClient like this:
import axios from 'axios';
const httpClient = axios.create({ baseURL: 'http://locahost:3003' });
...
export const httpClient = {
...
};
When I run it, I get error SyntaxError: Cannot use import statement outside a module which complains the line import axios from 'axios'. How can I get rid of this error? (I come from React-native world, I used the same thing in React-Native, it is fine)
The issue is by default express uses CJS format of importing as you might have seen const axios = require("axios").
What you are trying to do is an ESM format of import which is not understood by the JS as natively. To work import statements you can either add the following property to your package.json file - "type": "module" or you can use ".mjs" extension instead of default ".js" extension.
Hope this link helps further.
I have a typescript project which has uses one of our node modules which normally runs in our front-end. We are now looking to use this module in node on our server.
The module uses es6 import syntax import { props } from 'module/file'
When I include a ref in typescript using either of the following methods
import { props } from 'module/file';
var props = require('module/file');
I get the following error from typescript
unexpected token 'import'
(function (exports, require, module, __filename, __dirname) { import
It's a big job to re-write the module, and I've tried using babel with babel-plugin-dynamic-import-node, as well as SystemJS.
The problem with these systems is that they are all asynchronous, so I can't import the module in the standard fashion, so I would need to do a whole bunch of re-write when we get to the point that I can use import natively in node.js.
I can't be the first person to have this issue, but I can't seem to find a working solution.
--------------- update with set-up -------------
In response to #DanielKhoroshko's response. The original module I am trying to import is normally packaged by webpack in order to use on the front-end. I am now trying to use this same module both server-side and in the front-end (via webpack on the front-end) without re-writing the imports to use require and without running webpack to bundle the js to use on the server.
To be clear, the original module is written in JS, our service which is trying to use this module is written in typescript and transpiled. When the typescript tries to require the old module which uses import, it is at this point that we are running into the issue.
------------------ some progress ---------------------------
I've made some progress by creating a file in my imported module which uses babel in node.js to transpile the es6 code into commonJS modules.
I've done this via
var babel = require("babel-core")
var store = babel.transformFileSync(__dirname + '/store.js', {
plugins: ["transform-es2015-modules-commonjs"]
});
module.exports = {
store: store.code
}
I can now get the store in my new node.js project. However, the submodules within the store.js file are not included in the export.
So where in my module, it says
import activities from './reducers/activities';
I now get an error
Cannot find module './reducers/activities'
How can I get babel to do a deep traversal to include the sub-directories?
unexpected token 'import' means you are running es-modules code in environment that doesn't support import/export commands. If you are writing you code in TypeScript it's important to transpile it first before building for the browser or use ts-node to run it server-side.
If you are using webpack there are loaders ts-loader and awesome-typescript-loader
What is your setup?
To describe the module you would need to create an activities.d.ts file in the same folder where the js-version (I understood it is called activities.js and containers a reducer) resides with the following (approx.):
import { Reducer } from 'redux';
export const activities: Reducer<any>;
#Daniel Khoroshko was right in many ways, I ended up finding #std/esm which lets you import es6 modules and worked find for fetching the included imports as well.
var babel = require('babel-register')({
presets: ["env"]
});
require = require('#std/esm')(module);
var store = require('ayvri-viewer/src/store');
exports.default = {
store: store
}
I had to run babel to get a consistent build from es6 to node compatible es5
I'm building an isomorphic (universal) React.js app with Express.js. My server and client code share a Routes.jsx file employing ES2017 syntax and, well, JSX.
I understand babel-register should transpile this ; however, the following code generates an error when executed:
require('babel-register')({
presets: [
'es2017',
'react',
]
})
const routes = require('./Routes.jsx')
The first line of Routes.jsx is:
import React from 'react'
The error is:
(function (exports, require, module, __filename, __dirname) { import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
I am absolutely baffled at why this isn’t working. The correct babel modules are installed. Thanks for pointers!
The es2017 preset only includes newly added features for ES2017, so it will not include converting module syntax.
Using babel-preset-env is likely your easiest option.
I have a server written in node.js using node 6.10.2 and ecmascript. I want to upload it to heroku, locally when i rung the server with "npm start" the server starts without a problem, but on heroku I recevied the following error
import express from 'express';
SyntaxError: Unexpected token import
How can I fix this error?
Thanks
You have 2 options:
Use require() instead of import
Transpile your code
Node doesn't support the import keyword. In Node you import modules with the require() function. For example you can change this:
import express from 'express';
to this:
const express = require('express');
Or you can transpile the code e.g. with Babel if you really want to use import. See:
https://babeljs.io/
I have an old test project originally built with Express 2.X. I am moving it to Express 4.x and trying to insert Babel 6.x to experiment with ES6 features server-side.
The update to Express 4.x went OK. The original app works fine. The problems arise when I start adding ES6 features.
In particular, I want to substitute all require and module.export instructions with ES6 import {...} from... and export {...}.
Problem: I seem unable to import routes from external files into the main app.js file.
My app.js loads routes like so:
import { indexRoute } from './routes/index_route';
app.use('/', indexRoute);
Inside index_route.js I have:
"use strict";
import express from 'express';
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index_view', { title: 'Express' });
});
export { router }
This source code is OK for Babel, but node complains at startup:
Router.use() requires middleware function but got a undefined
I have two files like index_route.js, each one for a group of routes, and AFAIS they both import + modify + export the same router object. In any case, the export+import done using ES6 keywords returns undefined.
What am I doing wrong? Am I using the ES6 keywords on the wrong objects? Am I using obsolete instructions to configure the routes inside app.js?
The problem is that you are exporting router as named export router, but trying to import it as indexRoute.
You should either rename your export:
export { router as indexRoute }
or change your import:
import { router as indexRoute } from './routes/index_route';
Try this:
export default router;