I am unsure whether I am supposed to use the require version or the import version.
It doesn't state that in the documentation and I found a statement in a Github issue that
Mixing import and require is definitely discouraged. The only way for Rollup to handle require statements is with rollup-plugin-commonjs, but that plugin will skip any files with import or export statements.
which could be interpreted as: "You need to still use require otherwise the common-js plugin will ignore your file and things will not work." or as "always use import everything else would constitute mixing". So that really confused me.
Context
I am trying to import a CommonJS library (Citation-js) into a javascript module (really typescript but I hope this is not relevant here). Now the documentation of common-js tells me to do
const Cite = require('common-js');
which tells me that it is a commonjs library (right?). Therefore I added
import commonjs from "rollup-plugin-commonjs";
import { nodeResolve } from "#rollup/plugin-node-resolve";
to my rollup config and put plugins: [commonjs(), typescript(), nodeResolve()] into the configuration.
Now vscode stops underlining everything and building the website with rollup works again. But the compiled javascript simply states require('common-js') and my browser complains that require is undefined.
Uncaught ReferenceError: require is not defined
So I tried
import Cite from 'common-js';
instead. But that resulted in the rollup build failing with
[!] Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
node_modules/#citation-js/core/package.json (2:8)
1: {
2: "name": "#citation-js/core",
^
Now I could of course install that plugin. But I am not sure that is right, since the whole point of a tool like rollup should be that dependencies of dependencies should be resolved automatically right?
I have also tried
Can't import npm modules in commonjs with rollup : "require is not defined"
This seemed like it would fix my problem: Using Older Require Module With Rollup
But:
the rollup-plugin-node-builtins is apparently not maintained (npm protested with security vulnerabilities and I found this: https://github.com/rollup/rollup/issues/2881). EDIT: There is a new package rollup-plugin-polyfill-node replacing that I guess.
resolve is no longer a member of #rollup/plugin-node-resolve so I assume that this has become nodeResolve which I am already using...
EDIT: installing #rollup/plugin-json actually lets me build the site again (with a bunch of warnings)
(!) Missing shims for Node.js built-ins (which is not fixed by the rollup-plugin-polyfill-node above)
(!) Missing global variable names
(!) Circular dependencies
(!) Unresolved dependencies
not sure what to do about these warnings
Related
I am creating an app with Electron and Vue (using js not ts).
When I run the app using npm run electron:serve the app runs fine.
I now want to build a Windows exe so I can distribute my app. I have tried using electron-builder, electron-packager and electron-forge. Whenever I can get the build to finish, running the exe throws the cannot use import statement outside a module error (referring to the first import statement it finds, i.e. import { app, protocol, BrowserWindow } from 'electron').
I've tried adding "type":"module" to my package.json but (due a bug in Vue, according to this question), that throws Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]
I've also tried changing all my import statements to require but this doesn't work because some of the node modules I'm using use import and the error just throws for those instead.
I'm tearing my hair out over this. Where do I go from here?
UPDATE:
I have found a workaround for the Vue bug and posted my findings on the linked question. I can now add "type":"module" to my package.json.
However, I now get an error thrown when I run npm run electron:serve and from my built exe:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: <my_project_root>\dist_electron\index.js
require() of ES modules is not supported.
require() of <my_project_root>\dist_electron\index.js from <my_project_root>\node_modules\electron\dist\resources\default_app.asar\main.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.
To be clear, I'm not using require in any of my source code, but the compiled(?) version does?
What's going on here?
UPDATE 2:
As requested, here is a minimal reproducible example that maintains original folder structure, configs and package.json
How do you resolve "Cannot use import statement outside a module" from a dependency when the dependency isn't declared as a module?
I want to use the validator in Svelte/kit to validate emails. However, when importing the ESM version, I get the "Cannot use import statement outside a module" error. I'm using pnpm instead of npm or yarn.
import isEmail from 'validator/es/lib/isEmail'
/node_modules/.pnpm/validator#13.6.0/node_modules/validator/es/lib/isEmail.js:1
import assertString from './util/assertString';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:355:18)
at wrapSafe (node:internal/modules/cjs/loader:1039:15)
at Module._compile (node:internal/modules/cjs/loader:1073:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
at Module.load (node:internal/modules/cjs/loader:989:32)
at Function.Module._load (node:internal/modules/cjs/loader:829:14)
at Module.require (node:internal/modules/cjs/loader:1013:19)
at require (node:internal/modules/cjs/helpers:93:18)
at nodeRequire
It appears that validator is attempting to use the import statement, but it's package.json does not specify "type": "module". My guess is that this is the root cause of the error.
Debug steps
package.json has "type": "module"
Upgraded to latest version of node
Tried using the non-esm version of validator 'validator/lib/isEmail', but that causes other errors not related to this thread.
Related
SyntaxError: Cannot use import statement outside a module — this solution is for code you control, not for dependencies
"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 — this seems to be very similar, but I'm getting this error in node, not in the browser
Metadata
Node: v16.2.0
Sveltekit: v1.0.0-next.115
Validator: 13.6.0
Have you tried importing like this?
import validator from 'validator'
I tried reproducing your issue with latest SvelteKit. This works fine:
// index.svelte
<script>
import validator from 'validator';
let result = validator.isEmail('foo#bar.com');
console.log(result);
</script>
When I changed the import statement to:
import validator from 'validator/es/lib/isEmail'
I got the error from your question (Cannot use import statement outside a module).
Importing validator/es/lib/isEmail supposedly only imports a subset of the library. I'm not sure how much difference it will make; it might not make any difference. A slightly larger build beats a build that doesn't work. I suggest getting it working first, then optimize the build size if you really need to.
For those that happen to have the same problem while deploying with nodejs using typescript.
"type":"module" was already set in my package.json in the main project. I put the build directory on the server (created by npm run build).
working-dir
|--build
|--index.js
|--...
I thought i had to just run node build/index.js, as I thought everything was packaged.
Turns out I need to add a package.json into the working directory (I think it also works by putting it into the build directory).
server
+ |--package.json
|--build
|--index.js
|--...
// package.json
{
"type": "module"
}
Without more information, if your problem solely lies in a problem with code you are dependent on, consider short term using something like patch-package to make the necessary adjustment, and long term, open up a PR over at the validator.js repo!
for patch-package, just go add the "type": "module" to the package.json at node_modules/validator, and then run npx patch-package validator. You can then version control the outputted diff file, and the changes are made automatically with npm hooks assuming patch-package is a (dev) dependency.
The behavior or defect of the library here is probably from the devs more keeping in mind things like webpack that do esm imports on their own terms, and not with the node module resolution patterns that it appears svelte is using. or at least how the problem has gotten this far.(might be wrong about this!).
After reading their docs: https://github.com/validatorjs/validator.js#es6, it looks like the es part in the import is, so it can be treeshakable. You can fix this error, by just importing it normally:
import isURL from 'validator/lib/isURL';
Try importing like this
import { isEmail } from "validator"
Try to import like below
const {isEmail} = require('validator');
Although I am able to start the npm project using npm start without any issues with webpack or babel, once I run npm test, I find the following error related to testing App.js using App.test.js (where App.js imports ApolloClient):
TypeError: Cannot assign to read only property '__esModule' of object '[object Object]'
| import ApolloClient from 'apollo-boost';
| ^
at node_modules/apollo-boost/lib/bundle.cjs.js:127:74
at Array.forEach (<anonymous>)
at Object.<anonymous> (node_modules/apollo-boost/lib/bundle.cjs.js:127:36)
Essentially, I'm confused as to why I get an error when running the test but not when starting the project.
I've tried adding in a number of babel plugins to both .babelrc and in my webpack config file:
#babel/plugin-transform-object-assign
#babel/plugin-transform-modules-commonjs
babel-plugin-transform-es2015-modules-commonjs
However, I haven't been able to resolve the issue. My thinking was that this is related to the fact that the file that fails to compile was originally CommonJS.
I was only able to find something relatively similar here, https://github.com/ReactTraining/react-router/pull/6758, but I didn't find a solution.
Is there something that I'm missing specifically related to running tests? I should also mention I've tried frameworks other than Jest and ran into the same issue.
EDIT:
I removed everything from App.test.js except the imports to isolate the issue so it just contains the following:
import React from 'react';
import { shallow } from 'enzyme/build';
import App from './App';
UPDATE:
I was able to resolve the initial error by upgrading apollo-boost from version 0.3.1 to 0.4.2. However, I now have a different error that is similarly frustrating. I am using Babel 7 and have added the plugin #babel/plugin-syntax-dynamic-import to both my .babelrc and to my webpack.config.js files. Despite this, I get the following error related to the use of a dynamic import in App.js when running the Jest to test App.test.js:
SyntaxError: Support for the experimental syntax 'dynamicImport' isn't currently enabled
Add #babel/plugin-syntax-dynamic-import (https://git.io/vb4Sv) to the 'plugins' section of your Babel config to enable parsing.
I'm not sure if there is a parsing error or something else, but I've tried numerous things that have not worked. The closest discussion I could find related to this problem is, https://github.com/facebook/jest/issues/5920, however, the proposed solutions don't work for me.
UPDATE:
One thing that I'm trying is to avoid duplication of the babel options as right now they're both in .babelrc and in the babel-loader options within webpack.config.js. From what I found online (Whats the difference when configuring webpack babel-loader vs configuring it within package.json?), the way to make webpack use the settings in .babelrc is to not specify options. However, doing so results in the same error described above showing up only this time when running npm start. I will add that the project that was originally created using create-react-app, however, in order to support multiple pages, I needed to customize webpack's configuration and so ejected from it. I'm not sure why this is so convoluted.
its probably a babel configuration issue, I'm pretty sure jest needs to be compiled to work with create-react-app...
did you specify a setup file in package.json:
"jest": {
"setupFiles": [
"/setupTests.js"
]
}
and in setupTests.js:
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
It turns out that one of the components in the project's src directory had its own local package.json file even though it wasn't being used and was not installed as a local dependency in the top level package.json (instead imports were done using relative urls). For some reason, the existence of this file changed the behavior of webpack and other tools when starting and testing the project such that none of the top level configurations were used for files within directories with separate package.json files. Once I removed these local package.json files from the components sub-directory, all the prior issues were resolved. One hallmark of this problem is that compilation errors were not showing up for JavaScript files that weren't nested under an alternate package.json file.
Hopefully this is useful for anyone that encounters similar errors as I don't think the cause can be directly determined from the compiler messages alone.
I'm trying to use lodash in my web application. I have installed lodash using npm in my local project.
I plan on using the ES6 modules in my code.
Here is my main.js file:
import * as _ from "lodash";
_.each([1, 2, 3, 4], (i) => {
console.log('index each ' + i);
});
And I have included it in index.html as:
<script src="js/main.js", type="module"></script>
But I get the following error in the browser console.
Uncaught TypeError: Failed to resolve module specifier "lodash".
Relative references must start with either "/", "./", or "../".
Note: I do not wish to use any bundling tool.
If you don't wish to use any bundling tools, you will need to provide a path to the lodash folder within node_modules, relative to the JavaScript file that you have the import statement in.
If you do not wish to use a bundler, it would also be worthwhile importing from the specific file, the function you need. For example:
import _each from '../node_modules/lodash/each'
As of 2021, please consider the following statement by Márton Salomváry (Jan 2018):
Unfortunately even most libraries authored or published in ES6 module format will not work because they target transpilers and rely on the Node.js ecosystem. Why is that a problem? Using bare module paths like import _ from 'lodash' is currently invalid, browsers don’t know what to do with them.
And also the statement by Jake Archibald (May 2017):
"Bare" import specifiers aren't currently supported.
Valid module specifiers must match one of the following:
A full non-relative URL.
Starts with /.
Starts with ./.
Starts with ../.
And javascript.info:
In the browser, import must get either a relative or absolute URL. Modules without any path are called “bare” modules. Such modules are not allowed in import.
Certain environments, like Node.js or bundle tools allow bare modules, without any path, as they have their own ways for finding modules and hooks to fine-tune them. But browsers do not support bare modules yet.
Bundlers facilitate the use of "Bare Imports" which is not supported by the browser yet. Unless you bundle your code, I recommend using the solution proposed by #Asler. Besides, a lot of work is currently being done to study the implementation of "Bare Imports" in the browser, please follow this link if you want to monitor the overall progress.
Eventually you can't use JS modules on browser like that. These modules are for webpack or other bundler.
Try module lodash-es
import each from '../node_modules/lodash-es/each.js'
If you are trying to import css file, make sure to mention .css in import statement.
you can add your node_modules to the public dirs, so you can easily shorten your importing syntax from ../../../../node_modules/my-package into /my-package
also, you need to specify the full path including the file and the extension
import mod from "/my-package/file.mjs"
I am trying to use video.js via webpack.
I installed video.js via npm - npm install video.js --save-dev
In webpack I read that video.js should be loaded via script loader else it throws an error.
This is how I am loading video.js through the babel loader
module:
loaders: [
{
test: /video\.js/,
loader: 'script'
}
]
I got this solution from here https://github.com/videojs/video.js/issues/2750
This is my import statement
import videojs from 'video.js';
The issue that I now face is the import is returning an empty object, so when I try to do this:
var vidTag = ReactDOM.findDOMNode(this.refs.html5Video);
this.videojs = videojs(vidTag);
I get this error:
renderer-0.js:8031 Uncaught (in promise) TypeError: (0 , _video2.default) is not a function(…)
Any help will be much appreciated. I am new to ES6 / React / Webpack
Please take a look at the loader's README before copy&pasting some random code. The script-loader is not appropiate here, because it imports scripts into the global scope while skipping the whole module system.
So, if you wanted to use the script-loader, you would just write:
import "script-loader!video.js";
console.log(videojs); // should be an object now
Usually I would not recommend the use of the script-loader because it neglects the whole point of a module system where you import stuff explicitly into the local scope. In the example above, the import happens as a side-effect into the global scope which is effectively the same as just using a <script> tag with all its downsides like name clashes, etc.
There are often better alternatives to it, like the exports-loader, which appends a module.exports at the end of the module, thus turning an old-school global script into a CommonJS module.
In this particular case, however, you don't need a loader at all because video.js is already aware of a CommonJS module system. Just write import videojs from "video.js";.
There is another minor problem, however. If you compile this with webpack, it will print a warning to the console:
WARNING in ../~/video.js/dist/video.js
Critical dependencies:
13:480-487 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
# ../~/video.js/dist/video.js 13:480-487
This is because webpack detects that this file has already been bundled somehow. Often it's better to include the actual src with all its tiny modules instead of one large dist because this way webpack is able to optimize the bundle in a better way. I've written down an exhaustive explanation about how to import legacy scripts with webpack.
Unfortunately, video.js does not include its src in the version deployed at npm, so you're forced to use the dist. In order to get rid of the error message and to improve webpack's build time, you can instruct webpack to skip video.js when parsing the code for require() statements by setting the module.noParse option in your webpack.config.js:
module: {
noParse: [
/node_modules[\\/]video\.js/
]
}
Usually it's safe to flag all pre-bundled modules (typically those with a dist folder) as noParse because they are already self-contained.
include SDN
<script src="//vjs.zencdn.net/5.11/video.min.js"></script>
webpack config:
config.externals = {
'video.js': 'videojs'
};