Rollupjs Leave imports unchanged - javascript

My input file looks like this:
import * as chalk from 'chalk'
const chalkInstance = new chalk.Instance({
level: 1
})
My output file looks like this:
import { Instance } from 'chalk';
const chalkInstance = new Instance({
level: 1
});
The problem is that chalk is a commonjs module and I want to my output to be an es module so when I execute the file I get the following error: The requested module 'chalk' is expected to be of type CommonJS, which does not support named exports etc. Is there a way to prevent Rollup from changing the import * as something imports? The problem doesn't go away even if I disable treeshaking.
Thank you in advance!

Preserving the import as typed won't help you — you need to do import chalk from 'chalk' instead, since CommonJS modules only have a default export. If you do preserve the import you'll still get an error, it'll just be a different error:
const chalkInstance = new chalk.Instance({
^
TypeError: chalk.Instance is not a constructor

Related

node: getting error importing CommonJS module however I try to import it

I have a local node module, #em/inVis in my company whose index.d.ts file looks as follows:
import UWeb from "./UWeb";
import UWebParams from "./UWebParams";
export { UWeb, UWebParams };
elsewhere within the app, it's used as follows in typescript files
import { UWeb, UWebParams } from "#em/inVis";
when I try to do that in my TS file, I get the node error:
SyntaxError: Named export 'UWeb' not found. The requested module '#em/inVis' is a CommonJS module, which may not support all
module.exports as named exports. CommonJS modules can always be
imported via the default export, for example using:
import pkg from '#em/inVis'; const { UWeb, UWebParams } = pkg;
so when I try using that approach suggested above, I am getting the node error:
SyntaxError: Cannot use import statement outside a module not sure
what I am doing wrong.

How to publish a library to npm that can be used both with import and require?

tealium-tracker is written in es6 and transpiled using Babel before published to npm.
When consumers do:
import initTealiumTracker from "tealium-tracker";
everything works as expected.
However, some consumers want to use a require instead of an import, and have to append .default:
const initTealiumTracker = require("tealium-tracker).default;
How could I publish the library to avoid appending .default?
I want consumers to be able to do either:
import initTealiumTracker from "tealium-tracker";
or
const initTealiumTracker = require("tealium-tracker);
Source code
In your source code, If you are ok with using commonJS syntax for import and export...
One option would be to replace all import and export with require and module.exports. Looks like webpack doesn't allow mixing the syntaxes (ES6 and commonJS modules).
So your index.js file can require the functions from dependent module as
const { callUtag, flushUtagQueue } = require("./utagCaller");
and export the default function as
module.exports = initTealiumTracker;
module.exports.default = initTealiumTracker;
Likewise your dependent module can export the functions as
module.exports = { callUtag, flushUtagQueue };
This way, consumers should be able to use either
import initTealiumTracker2 from "tealium-tracker";
OR
const initTealiumTracker1 = require("tealium-tracker");

Jest vs React: module exports and "Jest encountered an unexpected token"

I am having problems getting React and Jest to work together which seems odd as I thought they both came from a similar origin. My issue is around the way that the class I'm testing is being exported.
I have an ArticleService class which I could use happily in React when it was exporting as default:
class ArticleService {
constructor(articles) {
this.articles = articles;
if (!this.articles) {
this.articles =
[//set up default data....
];
}
}
getAll(){
return this.articles;
}
}
//module.exports = ArticleService;//Need this for jest testing, but React won't load it
export default ArticleService;// Can't test with this but React will load it.
Here is how it is being called in my React app (from my HomeComponent):
import ArticleService from './services/xArticleService';
and is being used happily as
const articles = (new ArticleService()).getAll();
However my tests will not run. Here is my test with an import of the class file:
import ArticleService from "../services/xArticleService";
it('correctly gets all summaries', () => {
var summaries = getFakeSummaryList();
var testSubject = new ArticleService(summaries);
var actual = testSubject.getAll();
expect(actual.length).toEqual(10);
});
and I get
FAIL src/tests/ArticleService.test.js
Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
U:\...\src\tests\ArticleService.test.js:2
import ArticleService from "../services/xArticleService";
^^^^^^
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
If (in the test) I swop
import ArticleService from "../services/xArticleService";
for
const ArticleService = require('../services/xArticleService');
and edit the export in xArticleService.js to
module.exports = ArticleService;//Need this for jest testing, but React won't load it
then the tests are executed but React will not load it:
Attempted import error: './services/xArticleService' does not contain a default export (imported as 'ArticleService').
I have a default set up, creating using create-react-app. I've not changed any .babelrc.
Can anyone see where I am going wrong?
Thanks
UPDATE:
I have made the changes to .babelrc suggested in the accepted answer to the possible duplicate of this but this has made no change to the output.

express-validator usage with ESM modules

I tried to import into an ESM module with this syntax in Node.js v8.7.0 with --experimental-modules flag:
import { check, validationResult } from 'express-validator/check';
import { matchedData, sanitize } from 'express-validator/filter';
However I'm getting the following error:
(node:29028) ExperimentalWarning: The ESM module loader is experimental.
SyntaxError: The requested module does not provide an export named 'check'
at checkComplete (internal/loader/ModuleJob.js:86:27)
at moduleJob.linked.then (internal/loader/ModuleJob.js:69:11)
at <anonymous>
What is the correct usage with ESM modules turned on with --experimental-modules flag?
I tested with #std/esm package also. It only works of I turn cjs: true.
This happens because, in Node.js, CommonJS modules imported via import only have a default export*.
If the module you're importing is not an ES Module (which is the case of express-validator), then all you can do is something like this:
import checkAPIs from 'express-validator/check';
import filterAPIs from 'express-validator/filter';
const { check, validationResult } = checkAPIs;
const { matchedData } = filterAPIs;
* Source: https://medium.com/the-node-js-collection/an-update-on-es6-modules-in-node-js-42c958b890c
Use This...
import validator from 'express-validator'
const { check, validationResult } = validator
Now, when doing from 'express-validator/check', for example, it says, requires to express-validator/check are deprecated.You should just use require("express-validator") instead. 🙄 Ironically, so are CommonJS modules to some extent.
import validator from 'express-validator'
const { body } = validator

Webstorm ES6 named import getting cannot resolve symbol error

I have an error in Webstorm when using ES6 named import declaration:
import { nodes } from 'utils/dom';
I get "cannot resolve symbol" error on "nodes"
Also when I try to export as named export like this:
export {
write: document.write.bind(document),
node: document.querySelector.bind(document),
nodes: document.querySelectorAll.bind(document)
};
I get errors too.
I use eslint with babel-eslint parser.
The thing is that this works in Sublime Text 3 as a charm, but for some reason fails error checking in Webstorm.
I assume that this is because except Eslint webstorm is doing other code checking.
Any Idea how I can suppress that and use only eslint with babel-eslint parser?
Any advice will be appreciated
I get "cannot resolve symbol" error on "nodes"
is because utils/dom in standard Node code means "find dom.js inside a module called 'utils'. You have overridden this behavior by using webpack's moduleDirectories property, but WebStorm doesn't know what that is. For WebStorm to properly resolve utils/dom, you'll need to add the utils folder as a library in your webstorm project configuration.
Your export syntax is incorrect. ES6 import/export syntax is 100% unrelated to objects, and in your example export, you are using object syntax. import { nodes } is asking for an export named nodes. There are multiple ways that you could write the exports that you have:
export const write = document.write.bind(document);
export const node = document.querySelector.bind(document);
export const nodes = document.querySelectorAll.bind(document);
or alternatively you could collapse them if you like multiline var/let/const
export const write = document.write.bind(document),
node = document.querySelector.bind(document),
nodes = document.querySelectorAll.bind(document);
or even
const write = document.write.bind(document);
const node = document.querySelector.bind(document);
const nodes = document.querySelectorAll.bind(document);
export {write, node, nodes};
Hard to say if this is directly related, but for Webstorm to know how to resolve your imports, you can also go to Preferences > Directories and set folders as Resource Root (or right/context-click on a folder and set it that way)
This might need to be done, for example, when you've configured Webpack to resolve certain sub-directories, where your project structure might be:
/
/docs
/src
/containers
/app
App.js
/components
/header
Header.js
In which case Webstorm would expect an import in App.js to look like the following:
import Header from '../../../components/header/Header'
Whereas with Webpack, if you've added src as a module to resolve, you can do the following, which Webstorm doesn't currently understand, hence adding it as a Resource Root resolves the issue
import Header from 'components/header/Header'
Reference: Path aliases for imports in Webstorm

Categories

Resources