Can ES6 be used natively in webpack.config.js? - javascript

This answer:
How can I use ES6 in webpack.config.js?
seems to imply a transpilation step.
Can ES6 be used natively? How?
For example I tried to convert the simple example here from require to import and receive the following error
(function (exports, require, module, __filename, __dirname) { import path from 'path'
^^^^
SyntaxError: Unexpected identifier

You should use webpack-cli --config-register (-r) to allow that.
To use that flag, you must have babel-register installed. webpack --config-register babel-register --config ....
Another option is esm.

Related

How to support es modules and commonjs modules at the same time

Some packages we install from npm support both commonjs and es modules,
These packages can be imported as follows:
import express from 'express'
// or
const express = require('express')
I have created a package which I already published to npm using es modules.
and I since my another project which I'm working on is built with commonjs, I realized that I can not require it using the following syntax:
const stackPlayer = require('stack-player')
How can I support the two module systems in my package stack-player so that everyone around the world can use it?
Is there another method other than converting all of my project to es modules (which would be too complex since the project is 1 year old and is big enough to refuse the idea). ?
require() Usage
require() can, by default, only be used in CommonJS Modules. The built in method to import ECMAScript modules into CommonJS is using import(pathToFile).then(module => { }).
Support for require()
If you want to support require() for your package, you must provide a CommonJS module.
Here's a functioning example that demonstrates when and how to utilize require() or import(). There are some small differences how import() of a CommonJS module works compared to a ECMAScript Module. Especially that only the default property on the module object is available, when import() is used on a CommonJS file that exported something with module.exports.
index.js which imports different module types (from the demo above):(In case the stackblitz demo will be deleted:)
// executed as CommonJS module
console.time('');
import('./lib/example.cjs').then(({ default: example }) => {
console.timeLog('', 'import cjs', example() == 'Foo'); // true
});
import('./lib/index.mjs').then(({ example }) => {
console.timeLog('', 'import mjs', example() == 'Foo'); // true
});
try {
const example = require('./lib/example.cjs');
console.timeLog('', 'require cjs', example() == 'Foo'); // true
} catch (e) {
console.timeLog('', 'require cjs', '\n' + e.message);
}
try {
const example = require('./lib/index.mjs');
console.timeLog('', 'require mjs', example() == 'Foo');
} catch (e) {
console.timeLog('', 'require mjs', '\n' + e.message); // Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/lib/index.mjs not supported.
}
lib/example.cjs
module.exports = function example() {
return 'Foo';
};
lib/index.mjs
import example from './example.cjs';
export { example };
export default example;
Conditional Export for Packages
A conditional export can be supplied for packages to support require(), for example in a case where the CommonJS require() is no longer supported by your package. Refer to this link for more information.
The "exports" field allows defining the entry points of a package when imported by name loaded either via a node_modules lookup or a self-reference to its own name. It is supported in Node.js 12+ as an alternative to the "main" that can support defining subpath exports and conditional exports while encapsulating internal unexported modules.
package.json (example from the nodejs docs)
{
"exports": {
"import": "./index-import.js",
"require": "./index-require.cjs"
},
"type": "module"
}
If so, you have to provide two scripts: one for the CommonJS ("require": "filename") and one for the ECMAScript module ("import": "filename").
While index-require.js must provide the script via exports = ... or module.exports = ..., index-import.js must provide the script with export default.
Keyword Usage
You can only use specific keywords depending on the files module type.
CommonJS Modules
module.exports is used to define the values that a module exports and makes available for other modules to require. It can be set to any value, including an object, function, or a simple data type like a string or number.
exports, module
If you use them inside an ECMAScript module you'll get an undefined Error.
require()
require() inside ECMAScript modules is possible, but you have to use a workaround as mentioned in this answer or take a look at the docs for module.createRequire(fileName):
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
// sibling-module.js is a CommonJS module.
const siblingModule = require('./sibling-module');
If you call require() from within a CommonJS on an ECMAScript module, it throws a not supported Error:
Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/script.mjs not supported.
With a more detailed error message depending on the situation:
Instead change the require of script.mjs in /path/to/app.js to a dynamic
import() which is available in all CommonJS modules.
Or:
/path/to/script.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
Instead rename /path/to/script.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in /path/to/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).
ECMAScript Moduls (ESM)
export default is used to export a single value as the default export of a module. This allows for a more concise way to import values, as the import statement can omit the curly braces when importing the default export.
Named exports, on the other hand, allow multiple values to be exported from a module. Named exports use the export keyword followed by an identifier and a value. (export const foo = "bar")
import ... from ...
It can handle CommonJS files and interprets them as if you would've used require().
Example based on express:
import express, { Route, Router } from 'express'; // EJS
// is similar to:
var express = require("express"), { Route, Router } = express; // CJS
Both CommonJS and ECMAScript modules support the import() function, but the returned object can have more properties on ESM files.
Summary:
CJS modules don't need to be converted to ESM, as they can be imported into ESM using the import ... from ... syntax without any modifications to the CJS module. However, it's advisable to write new modules using ECMAScript Module syntax, as it is the standard for both web and server-side applications and enables seamless use of the same code on both sides the browser/client-side and node/server-side.
Specifications
Additionally, I find this article on CommonJS vs. ES modules in Node.js from logrocket.com to be very informative. It delves into the pros and cons of ECMAScript compared to CommonJS in more depth.
Links:
MDN: import()
NodeJS.org: Difference between ECMAScript modules and CommonJS modules
There are two main scenarios:
1. Your package is written using CommonJS (CJS) module loading
This means your package uses require() to load dependencies. For this kind of package no special work is needed to support loading the package in both ES and CJS modules. ES modules are able to load CJS modules via the import statement, with the minor caveat that only default-import syntax is supported. And CJS modules are able to load other CJS modules via the require() function. So both ES modules and CJS modules are able to load CJS modules.
2. Your package is written using ES module loading
This means your package uses import to load dependencies. But don't be fooled - sometimes, especially when using TypeScript, you may be writing import in your code, but it's getting compiled to require() behind the scenes.
Unfortunately, CommonJS modules do not support loading ES modules except (in Node.js) by using the import() function (which is a bit painful and not a great solution).
In order to support CommonJS in this case, your best bet is to transpile your package into a CommonJS module, and ship both CommonJS and ESM versions of your package.
I do this in a number of my own packages mostly by using Rollup, which makes it relatively easy.
The basic concept is this:
Write your package as an ES module.
Install rollup: npm i -D rollup
Run npx rollup index.js --file index.cjs --format cjs to convert your code into a CJS module.
Export both from your package.json:
{
"name": "my-package",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"exports": {
"import": "./index.js",
"require": "./index.cjs"
}
}
This way, the CJS module loader knows to load your index.cjs file, while the ESM loader knows to load your index.js file, and both are happy.

How to move to ESM

I am using Egg framework for my NodeJs(v14.15.4) application
I want to use latest version of p-debounce library, the package is now pure ESM, Instead of const pDebounce = require('p-debounce') I must use import pDebounce from 'p-debounce' that not works on EggJs
If I use import
(node:10636) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
test.js:5
import pDebounce from 'p-debounce'
^^^^^^
SyntaxError: Cannot use import statement outside a module
If I use require
internal/modules/cjs/loader.js:1080
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: .\node_modules\p-debounce\index.js
require() of ES modules is not supported.
require() of .\node_modules\p-debounce\index.js from .\test.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from .\node_modules\p-debounce\package.json.
If I add "type": "module" in the package.json
const path = require('path');
^
ReferenceError: require is not defined
I have many require in my application and not want to change all to import at the moment
What is "type": "module" in the package.json ?
How can I fix the error?
You seem to be overlooking a particular point in the changelog you linked:
If you cannot move to ESM yet, don't upgrade to this version.
As you've pointed out, your application has already progressed significantly, and you have many require that you do not want to change at the moment. There is no need to upgrade to the latest version of p-debounce at this time, according to your needs.
When you do decide to migrate to ESM format, in order to upgrade individual files one at a time, you can use the .mjs extension to treat the code as an ECMAScript module.
ES modules are the future.
There is a way around in ES modules to require a common.js module. Using createRequire
WORKING EXEMPLE
axios-curlirize is ES module and axios support both.
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const axios = require('axios');
import curlirize from 'axios-curlirize';
curlirize(axios);
const { data } = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
console.log(data)
Using ES modules you can use top-level await without function.

Node --experimental-modules - Error: Cannot find module

I am getting an error when trying to import a local file, though no problem when using npm packages.
server.js
import express from 'express'
import next from 'next'
import apis from './src/server/api'
api.js
export default {
ello: 'bye',
jamie: 'hey'
}
Starting app
node --experimental-modules --inspect server.js
Error
For help, see: https://nodejs.org/en/docs/inspector
(node:20153) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/esm/default_resolve.js:59
let url = moduleWrapResolve(specifier, parentURL);
^
Error: Cannot find module '/var/www/goldendemon.hutber.com/src/server/api' imported from /var/www/goldendemon.hutber.com/server.js
at Loader.resolve [as _resolve] (internal/modules/esm/default_resolve.js:59:13)
at Loader.resolve (internal/modules/esm/loader.js:70:33)
at Loader.getModuleJob (internal/modules/esm/loader.js:143:40)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:43:40)
at link (internal/modules/esm/module_job.js:42:36) {
code: 'ERR_MODULE_NOT_FOUND'
}
I'm answering my own question if anybody else has this problem.
It turns out in experimental mode you need to define the full path with extension. So I am trying to import index.js thinking it will know.
To fix it:
import express from 'express'
import next from 'next'
import api from './src/server/api/index.js'
on node 12 you have 2 options:
use type="module" on package.json, experimental modules and specify extensions with specidier-resolution like this:
node --experimental-modules --es-module-specifier-resolution=node src/index
or not using specifier-resolution. Keep in mind you'll have to specify the extension of your files every where.
It should also work if you name your module file with a .mjs extension. Also, other ways to enable ESM are mentioned here.
Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:
Files ending in .mjs.
Files ending in .js, or extensionless files, when the nearest parent package.json file contains a top-level field "type" with a value of "module".
Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.
Or do like I did and just use transpilation the minute your source code deals with ES style module imports or some other non-standard JavaScript code, (E.g. TypeScript) on Node. For reference see this quick bash script I wrote, saved as .script/run-it.sh inside of my Node project:
#!/bin/bash
script=$1
out_path==/tmp/$script-out.js
npx esbuild --platform=node --bundle --outfile=$out_path $script
node $out_path
I added it as a run script in my package.json:
"scripts": {
"test": "sst test",
"start": "sst start",
"build": "sst build",
"deploy": "sst deploy",
"remove": "sst remove",
"run-it": "./.script/run-it.sh"
},
And my target script (import-test.js), what I want to emit/transpile as JavaScript code:
import { default as myImport } from './lib/index.js'
console.log(myImport)
And now I run it:
$ npm run run-it ./import-test.js
> my-nop#0.1.0 run-it /Users/jmquij0106/git/a-rebalancing-act
> ./.script/run-it.sh "./import-test.js"
[Function: main]
Bottomline is spare yourself the pain and just emit CommonJS compliant code whenever dealing with ES Modules on Node.js, see this comment/issue.

How to use ES6 modules inside jest.config.js files

I have a bunch of files that are configuring my Jest tests. I need them to specify environment for Puppeteer browser and setup/teardown behaviours.
module.exports = {
globalSetup: './jest-config/setup.js',
globalTeardown: './jest-config/teardown.js',
testEnvironment: './jest-config/puppeteerEnv.js',
testResultsProcessor: './jest-config/testResultsProcessor.js',
};
Right now i have a .babelrc file inside my repository with "env" preset and it transpiles my tests files and allows to use imports inside my code. Although jest-config files are not affected by transpilation and i can't use there preferred syntax.
/jest-config/teardown.js:1
(function (exports, require, module, __filename, __dirname) { import
TestResultManager from '../helpers/testResultsManager';
SyntaxError: Unexpected token import
Is there any possibility that I can use the import syntax in jest-config files such as teardown/setup or reporters?
Thanks.

Do I still need babel with NodeJs5?

As far as I know node 5 supports ES2015, but when I try to run something like
import sizeOf from 'image-size';
I get
$> node -v
v5.9.0
$> node test.js
/Users/dev/tmp/test.js:1
(function (exports, require, module, __filename, __dirname) { import sizeOf from 'image-size';
^^^^^^
SyntaxError: Unexpected token import
...
Now, when I search google, I find suggestions using babel
(using a .babelrc with an es2015 preset), but if node5 supports ES2015, why do I need babel ?
if node5 supports ES2015, why do I need babel
Node doesn't support every feature of ES2015 yet. For the unsupported features you might want to use Babel, or simply not use the feature.

Categories