Babel ES6 import error, SyntaxError: Unexpected token import - javascript

I am trying to set up a basic modular program, however I seem to be running into issues with importing modules. I attempt to import my custom module, I get the following error:
(function (exports, require, module, __filename, __dirname) { import testStep from 'testStep';
^^^^^^
SyntaxError: Unexpected token import
The code that is causing the issue:
testcase.js
import testStep from 'testStep';
testStep.hello();
testStep.js
var testStep = {
hello: hello,
};
var hello = () => {
console.log('hello world');
};
export default {testStep};
package.json
{
"name": "rebuild-poc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-polyfill": "^6.23.0",
"babel-preset-env": "^1.6.0"
},
"dependencies": {}
}
.babelrc
{
"presets": [
"env"
]
}
I have already tried several other fixes, such as setting testStep as a class, as well as using require('./testStep.js'), however neither of those seem to have worked.
Do I have something set up incorrectly with babel or in one of my files?
***Edit: I am running testCase.js with node testCase.js.

Please install babel-cli and call your file with: ./node_modules/.bin/babel-node testcase.js
It will fail. Now we have to fix your code.
testStep.js should look like:
var hello = () => {
console.log('hello world');
};
var testStep = {
hello: hello,
};
export default testStep;
Then, it will work. ;)
This first introduction on https://babeljs.io/ is, that you should install babel-cli and babel-preset-env. ;)
You can also write your testStep.js like this:
var testStep = {
hello: hello,
};
function hello () {
console.log('hello world');
};
export default testStep;
This keeps the hoisting in mind. Like Jacob said in his first point.

From the babel 6 Release notes:
Plugin Presets
$ npm install --save-dev babel-preset-env
save it .babelrc file
{
presets: ["env"]
}
Note:
https://babeljs.io/docs/en/babel-preset-env#docsNav

You need to define hello with function, using var, you will not have function hoisting, so when declaring testStep, hello is undefined.
If you want to use es module, you can use babel-register or babel-node.
In your code, node can not handle es module.
Babel-register
With bebel-register, all your module will be handled by babel when they are imported.
First,yarn add babel-register babel-cli --dev or npm install babel-register
babel-cli -dev
Then create an entry file:
// entry.js
require('babel-register')
require('testcase')
In your testcase, you can use es module now.
Edit you package.json:
"scripts": {
"test": "node entry.js"
},
you can run yarn test or npm run test in terminal.
You don't need babel-polyfill, that is for browsers, not for node.

Related

Cannot Import My NPM Package With ES6 Import/Export Syntax

I am creating an NPM package called notifman. Here's what I did:
Created the package.json:
{
"name": "notifman",
"version": "1.0.5",
"description": "Advanced, Lightweight and Powerful Notification Library For Plain JS",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "npx nodemon index.js"
},
"keywords": [
"notification",
"frontend",
"js",
"plain"
],
"author": "...",
"license": "MIT",
"dependencies": {
"notifman": "^1.0.3"
},
"devDependencies": {
"nodemon": "^2.0.20"
}
}
I wrote the index.js:
console.log("hello world");
Wrote a README.md
Tested the package in Node.js and it worked fine.
Originally, I wanted the package to work in the browser, so I tried changing the code in index.js to:
export default function getRoot() {
return document.getElementById("root");
}
Then, I wanted to test using import/export syntax, I suppose it is:
import getRoot from "notifman";
getRoot.textContent = "hello world";
The error message is:
Uncaught TypeError: Failed to resolve module specifier "notifman". Relative references must start with either "/", "./", or "../".
Partially Solved:
I just used Webpack, and it worked fine. But I am sure Webpack is not required. I want it to work WITHOUT webpack. This is why this is partially solved.
"type": "module"
**add this to your package.json just below main **

How to import js module when Typescript declaration file is located in a separate directory?

Question:
When I run npm run build with the configuration below, rollup.js is unable to resolve the dependency (import) and displays the following message below. Is there any way to make rollup happy while also referencing the Typescript declaration file?
Message from rollup:
(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
pdfjs-dist/types/web/ui_utils (imported by index.ts)
Here is my index.ts:
import { RendererType } from 'pdfjs-dist/types/web/ui_utils'
const renderType = RendererType.CANVAS;
My package.json:
{
"name": "myproject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "rollup --config"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#rollup/plugin-node-resolve": "^13.2.1",
"#rollup/plugin-typescript": "^8.3.2",
"pdfjs-dist": "^2.13.216",
"rollup": "^2.70.2",
"typescript": "^4.6.4"
}
}
My rollup.config.js:
import typescript from '#rollup/plugin-typescript';
import { nodeResolve } from '#rollup/plugin-node-resolve';
export default [
{
input: 'index.ts',
output: {
format: 'es',
file: 'index.js'
},
plugins: [
typescript(),
nodeResolve({ browser: true })
]
}
]
Here are the exact steps to reproduce the error above:
Create an empty folder and then run npm -y init
Run the following command:
npm install typescript pdfjs-dist rollup #rollup/plugin-node-resolve #rollup/plugin-typescript --save-dev
Add "build": "rollup --config" to your package.json
Create the rollup.config.js file shown above
Run npm run build in the terminal
More background:
Now, I should point out that the file pdfjs-dist/types/web/ui_utils is a typescript declaration file (ui_utils.d.ts). The actual js file is in pdfjs-dist/lib/web.
If I copy the typescript declaration file so that it is located in the same directory as the js file, dependency resolution works. However, since I will be writing a wrapper around pdf js, I would have to do this for every typescript declaration file which is very tedious and upgrading would also become an issue.
So another way to word the question would be how to resolve a module *.d.ts when the js file is located in another directory?
I came up with the following solution to the problem.
Create a d.ts with the following and name it the same as the module name (ui_utils.d.ts in my case)
declare module 'pdfjs-dist/lib/web/ui_utils' {
export * from 'pdfjs-dist/types/web/ui_utils'
}
Using the above, now I can reference the actual location of the module and Typescript will pick up the declarations as well.
import { RendererType } from 'pdfjs-dist/lib/web/ui_utils'
Side note: When using rollup, you may also need to use #rollup/plugin-commonjs to be able to resolve dependencies.

Node doesn't support import/export even if --experimental-modules is set

I am trying to get Node to handle import/export, but I getting syntax errors in the import statement at "import $" -> Unexpected identifier
Node:
node start.js --experimental-modules
start.js:
(() => {
import $ from "SCRIPT//CommonImport";
});
commonImport.js:
(() => {
export var $ = require("jquery");
});
package.json:
{
"type": "module",
"name": "lc.assets.hyper",
"version": "1.0.0",
"description": "brand new UI for LC Assets",
"main": "start.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Stein Lundbeck",
"license": "ISC",
"devDependencies": {
"jquery": "^3.4.1"
}
}
You have to declare all imports at the top of the file like this:
import $ from "/my/path"
And you can't use export statements inside of functions, they have to be declared in the upper scope of your module. And you can't use require (CommonJS) if you're using ES6 import/export, but you can use export ... from ... construction:
export {default as $} from "jquery"
If you want to import modules dynamically you'll have to do it like this:
async function myFunc() {
const exportedVar = await import('/my/path')
}
Note that import() returns a Promise, i.e. it is async operation, not synchronous as require.
Also note, you can't use export dynamically like import()
Using the esm module did the trick.
Install:
npm install esm --save-dev
Use:
node -r esm start.js

Option "setupTestFrameworkScriptFile" was replaced by configuration "setupFilesAfterEnv", which supports multiple paths

Option "setupTestFrameworkScriptFile" was replaced by configuration "setupFilesAfterEnv", which supports multiple paths.
Please update your configuration.
I found this exact question here: setupTestFrameworkScriptFile is not supported error
I renamed my jest.config.js to setUpTests.js however that did not remove the deprecated error warning.
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })
package.json scripts
"scripts": {
"dev": "next -p 7777",
"build": "next build",
"start": "next -p 7777",
"test": "NODE_ENV=test jest --watch --no-cache",
"test-win": "SET NODE_ENV=test&& jest --watch"
}
"#types/enzyme": "^3.1.15",
"#types/jest": "^23.3.13",
"jest": "^24.1.0"
Jest used to have a config option called setupTestFrameworkScriptFile...
...but it was deprecated in favor of the newer setupFilesAfterEnv in PR #7119 which shipped with version 24.0.0.
Since you are using Jest ^v24.1.0 you will need to use setupFilesAfterEnv.
Just find where setupTestFrameworkScriptFile is used in your Jest config, rename it to setupFilesAfterEnv, and put the single file it used to point to in an array and you should be good to go.
Example, change this jest.config.js:
module.exports = {
...
setupTestFrameworkScriptFile: './setup.js',
...
}
...to this:
module.exports = {
...
setupFilesAfterEnv: ['./setup.js'],
...
}
If you are using create-react-app, change the key name at package.json file
from
"jest": {
// ...
"setupTestFrameworkScriptFile": "<rootDir>/src/setupTests.js",
to
"jest": {
// ...
"setupFilesAfterEnv": ["<rootDir>/src/setupTests.js"],
After I changed my file name from setupTests.js to setup.tests.js it worked. Maybe the dir path name did not match. Make sure you check that!
In my case in 'jest.config.js' I had
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts']
correctly referencing 'setup-jest.ts' in <rootDir>.
After renaming the file itself and the reference to it from
setup-jest.ts
to
setupJest.js
the error message vanished. Weird. Seems as if the hyphen in the file-name or being the same as in 'node_modules.jest-reset-angular.setup-jest.js' was the culprit.
Using Angular 13 and Jest (in package.json):
"jest": "^28.1.0",
"jest-preset-angular": "^12.1.0",
I'm on Lubuntu 22.04.
Jest message is not mantained anymore: https://github.com/mattphillips/jest-expect-message/issues
So I suggest using:
const msg = '... my message...'
expect({msg, result}).toEqual({msg, result: expected})
From https://github.com/facebook/jest/issues/3293
Or alternatively
function expectToBeTrue(result: any, message: string){
return expect({message, result}).toBe({message, result: true})
}
expectToBeTrue(compute() == 1, "Oh no compute should return 1!")

Meteor + LitElement (Polymer 3) issue with importing

I had an issue with importing the LitElement module into a Meteor project:
I'm starting a new test project with Meteor 1.7+ and am using LitElement for a few components.
I installed Meteor like so:
meteor create meteor-lithtml --release 1.7.1-beta.29 --bare
I installed like so:
meteor npm install --save #polymer/lit-element
My node_modules directory looks like so:
My package.json file:
{
"name": "myapp",
"private": true,
"scripts": {
"start": "meteor run"
},
"dependencies": {
"#babel/runtime": "^7.0.0-beta.56",
"#polymer/lit-element": "^0.5.2",
"#vaadin/router": "^1.0.0",
"meteor-node-stubs": "^0.4.1",
"redux": "^4.0.0"
},
"meteor": {
"mainModule": {
"client": "client/index.js",
"server": "server/index.js"
}
}
}
The typical way I see lit-element imported is not working...
Just adding an index.js file and importing the lit-element module generates errors. If I remove the import from the index.js file, the errors go away.
\\ client\index.js
import { LitElement, html } from '#polymer/lit-element';
The very first error:
Uncaught SyntaxError: Unexpected token {
modules.js?hash=182125a3fa97eaa24f6d313584ca593c3aed2103:984
Points to this location:
Expanding node_modules to look into this file:
Why am I getting the unexpected { token?
NOTE: I'm asking this question here just in case a Meteor user stumbles by with the same issue and needs help.
Just in case we have any more Meteor users stop by with an issue like this, here are the references to the explanation & solution:
explanation: https://forums.meteor.com/t/litelement-import-litelement-html/45042/8?u=aadams
solution: https://github.com/aadamsx/meteor-lithtml/pull/1

Categories

Resources