Yarn/Node - JavaScript - Issues with Import and Export - javascript

I want simply import a function from an another file and I'm getting this error message:
SyntaxError: Cannot use import statement outside a module
I'm not using any html file. I'm using only js files with webpack that returns the result on the console with yarn start
Here is the code of the file that contains the function I want to export:
export function assert(value, desc) {
return value ? console.log(desc) : console.log('fail')
}
Here is the code of the file that I want to import the function:
import {assert} from './assert.js'
function juggle() {
var result = 0;
for(var n=0; n < arguments.length; n++) {
result += arguments[n]
}
this.result = result
}
var ninja1 = {}
var ninja2 = {}
juggle.apply(ninja1, [1,2,3,4])
juggle.call(ninja2, 5,6,7,8)
assert(ninja1.result === 10, "juggled via apply")
assert(ninja2.result === 26, "juggled via call")
Here is my package.json:
I don't know if it is userful to solve this issue, but here is, if you want to see it.
{
"name": "c",
"version": "1.0.0",
"main": "",
"scripts": {
"start": "node Cap_03/01_apply_e_call.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"webpack-dev-server": "^3.9.0"
},
"type": "module",
"devDependencies": {
"webpack": "^4.41.2"
},
"description": ""
}

As of Node 13.2.0+
Verify that you have the latest version of Node installed. Simply do one of the following:
Add "type": "module" to the nearest parent package.json. With this, all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.
OR
Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.
If you use an older Node version or have to
import statements are permitted only in ES modules.
For similar functionality in CommonJS, see import().
To make Node treat your file as a ES module you need to
add "type": "module" to package.json
add "--experimental-modules" flag to the node call

Related

Babel.js: Uncaught TypeError: _interopRequireDefault is not a function

I use the babel.js node.js API to compile react jsx and js scripts.
I have the following node.js script for example:
// react_transform.js
const fs = require("fs");
code = fs.readFileSync("./samples/sample4.js", 'utf8');
result2 = require("#babel/core").transformSync(code, {
presets: [
"#babel/preset-env",
"#babel/preset-react",
],
plugins: [
"#babel/plugin-transform-runtime",
],
});
fs.writeFileSync(`./out/out4.js`, result2.code);
console.log("y.");
And the input file that has the jsx code is like:
// sample4.js
ReactDOM.render(
<div>
<p>
hoge.
</p>
</div>
,
document.getElementById('root')
);
$(".__upvote").click(async function (e) {
alertify.warning("You need to login.");
});
Without the "#babel/plugin-transform-runtime", line in the node.js script, when I use the script on the browser (where the output code should be located in the production), it causes an error:
VM496:9 Uncaught ReferenceError: regeneratorRuntime is not defined
So, I did research and added the line. But now I started to get a new error:
VM830:5 Uncaught TypeError: _interopRequireDefault is not a function
By the way the output js file is as follows:
// out4.js
"use strict";
var _interopRequireDefault = require("#babel/runtime/helpers/interopRequireDefault");
var _regenerator = _interopRequireDefault(require("#babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("#babel/runtime/helpers/asyncToGenerator"));
ReactDOM.render( /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("p", null, "hoge.")), document.getElementById('root'));
$(".__upvote").click( /*#__PURE__*/function () {
var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(e) {
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
alertify.warning("You need to login.");
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}());
So I again did research about the new error, found an SO post:
reactjs - How to fix TypeError _interopRequireDefault is not a function in Create React App - Stack Overflow
People say:
Add #babel/runtime to the dependency section. That will fix it.
After add "#babel/runtime", I fixed it
So I added that "#babel/runtime" to package.json then npm install-ed. Now the package.json is like (I ommited irrelevant lines):
{
"name": "tmp",
"version": "1.0.0",
"description": "",
"main": "lodash_dev.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"#babel/runtime": "^7.17.8",
},
"devDependencies": {
"#babel/plugin-syntax-dynamic-import": "^7.8.3",
"#babel/plugin-transform-react-jsx": "^7.17.3",
"#babel/plugin-transform-runtime": "^7.17.0",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
}
}
Then re-run the node.js script, I get the output, I tested it on the page on the browser, however, for some reason the error still persists.
How can I fix this? Thanks.
You're transforming your code with Babel, but you're not running a bundler such as esbuild or webpack.
require() is not a thing in the browser. The bundler's responsibility (among other things) is to take all of those require() calls and resolve them into real modules, and end up with one (or more) .js files that contains all of the require()d code and no require()s.

How to correctly use import in Node JS

I added "type": "module" to package.json. I was under the impression no translation between ES6 and CommonJS was necessary with the newer versions of node to use import, in this case v16.0.0.
What do I need to change to get import to work?
I have 3 simple files in the same directory.
package.json
main.js
Utility.js
package.json
{
"name": "node_template",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"type": "module"
}
Utility.js
'use strict';
class Utility {
constructor() {
}
}
export { Utility };
main.js
"use strict";
(async ()=>{
import { Utility } from './Utility.js';
var utility = new Utility();
console.log( "Main" );
})();
When I run "node main.js" I get the following error:
node -v
v16.0.0
node main.js
main.js:4
import { Utility } from './Utility.js';
^
SyntaxError: Unexpected token '{'
←[90m at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18)
←[39m
←[90m at async link (node:internal/modules/esm/module_job:64:21)←[39m
main.js
(async () => {
let { Utility } = await import('./Utility.js');
let utility = new Utility();
console.log('main');
})();
Note:
The import statement you used, should only be used at top-level of the module. But you can dynamically or conditionally import module by using dynamic import - import(). See the links below for more detail.
Links:
https://v8.dev/features/dynamic-import
https://flaviocopes.com/javascript-dynamic-imports/

local modules node.js :can't load files other than index.js

I am trying to learn local module setup in my express js application.
test-module folder is created in my project folder and it contains two files
1)index.js
module.exports = {
indexfunc:function(){
console.log('ok from index');
}
}
2)hello.js.
module.exports = {
helloFunc:function(){
console.log('ok from hello');
}
}
importing this module in app.js file
var mymodule = require('hello-module');
console.log(mymodule);
output:{ indexfunc: [Function: indexfunc] }
But this returns console.log(require('hello-module').hello) undefined.
package.json for this module
{
"name": "hello-module",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Since hello is a file in hello-module, you need to pass it as the path to require. Do:
console.log(require('hello-module/hello'))
By doing :
console.log(require('hello-module').hello)
You are printing the hello property exported by index.js
I addition to #Ayush answer, if your goal is to execute code from other files in a module folder you can export a reference like so :
//index.js
const helloModule = require('./hello');
module.exports = {
hello: helloModule,
indexfunc:function(){
console.log('ok from index');
}
}

babel.transform() function not using .babelrc or package.json config

I am trying to use Babel to transform ES6 to ES5 that is already loaded into a variable. However, I am finding contrary to the Babel documentation babel.transform() is not using the configuration files to transform the code.
The following demonstrates my issue:
package.json:
{
"name": "babel-test",
"version": "1.0.0",
"main": "index.js",
"babel": {
"presets": [
["env", {
"targets": {
"ie": 8
}
}]
]
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-preset-env": "^1.6.1"
}
}
test.js:
const a = 0
index.js:
const babel = require('babel-core')
console.log(babel.transform('const a = 0').code)
console.log(babel.transformFileSync('test.js').code)
CLI:
$ node index.js
const a = 0;
"use strict";
var a = 0;
As you can see babel.transformFileSync() is using the config and babel.transform() isn't.
How do I get babel.transform() to use the config file?
.babelrc files are searched for relative to the file being compiled, so if it doesn't know the name of the file, it can't find it.
babel.transform('const a = 0', {filename: "test.js"}).code)
for instance will work.

Using d3-tip with npm: "Uncaught TypeError: Cannot read property 'node' of undefined"?

I've installed d3": "^3.5.17" and "d3-tip": "^0.7.1" using npm (d3-tip documentation). Then in my index.js file I have this code:
var d3 = require('d3');
var d3tip = require('d3-tip')(d3);
console.log('d3 version', d3.version);
var tip = d3tip().attr('class', 'd3-tip').html(function(d) { return "hello world"; })
But when I build the index file with browserify and load it in the browser, I see an error from the var tip line:
index.js:247 Uncaught TypeError: Cannot read property 'node' of undefined
This is coming from this function in the d3-tip source code:
function getSVGNode(el) {
el = el.node()
if(el.tagName.toLowerCase() === 'svg')
return el
return el.ownerSVGElement
}
It looks like this function is expecting a node to be passed to it? But where would this come from?
The build itself does not throw any errors, and I think I'm requiring d3-tip correctly, as per this question. The console statement shows d3 version 3.5.17, as expected.
UPDATE: Here's my package.json file:
{
"name": "myapp",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "watchify index.js -o main.js --debug --verbose",
"build": "browserify index.js | uglifyjs > main.min.js"
},
"dependencies": {
"d3": "^3.5.17",
"d3-tip": "^0.7.1",
"datatables.net": "^1.10.12",
"datatables.net-bs": "^1.10.12"
},
"devDependencies": {
"uglifyjs": "^2.4.10",
"watchify": "^3.2.1"
}
}
And I installed the files with npm install.
This was happening because I was trying to use the latest version of d3-tip (which requires v4 of D3) with v3 of D3.
Reverting to older versions of both fixed things:
"d3": "^3.5.17",
"d3-tip": "^0.6.7"
Your line
var tip = d3tip().attr('class', 'd3-tip').html(function(d) { return "hello world"; })
must be
var tip = d3.tip().attr('class', 'd3-tip').html(function(d) { return "hello world"; })
You can check my implementation #:
Source (Lines: 17, 91, 333-339, 685-692)
Demo
The problem is your line:
var d3tip = require('d3-tip')(d3);
You should not be calling d3.tip(foo) with the d3 reference itself, but with a d3 selection (which it can then invoke .node() on).
I think this should probably be:
d3.tip = require('d3-tip');

Categories

Resources