browserify error when using npm dependency that is es6 style [duplicate] - javascript

I'm working with Babelify and Browserify. Also, I'm using ES6 style module features by node module system.
I would like to put all my own modules into node_modules/libs.
For instance:
test.js in node_modules/libs
export default () => {
console.log('Hello');
};
main.js (will be compiled to bundle.js)
import test from 'libs/test';
test();
After that, I have compiled the above codes to bundle.js with this command:
browserify -t babelify main.js -o bundle.js
But unfortunately, I have got some error:
export default () => {
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'
Directory structure:
[test]
`-- node_modules
│ `-- libs
│ `-- test.js
`-- main.js
But, when own modules not in node_modules like this:
[test]
`-- libs
│ `-- test.js
`-- main.js
Then, it works fine. How can I use the ES6 style modules with babelify in node_modules?

That is how Browserify transforms work, transforms only have an effect directly in the module that is being referenced.
If you want a module in node_modules to have a transform, you'd need to add a package.json to that module and add babelify as a transform for that module too. e.g.
"browserify": {
"transform": [
"babelify"
]
},
inside your package.json plus babelify as a dependency will tell browserify to run the babelify transform on any file inside that module.
Having libs be a folder in node_modules is however probably a bad idea. Generally that folder would have true standalone modules in it. I'd generally say that if the folder can't be taken and reused elsewhere, then it shouldn't be in node_modules.
Update
For Babel v6, which was recently released, you will also need to specify which transformations you would like to perform on your code. For that, I would recommend creating a .babelrc file in your root directory to configure Babel.
{
"presets": ["es2015"]
}
and
npm install --save-dev babel-preset-es2015

You can specify source transforms in the package.json in the
browserify.transform field. There is more information about how
source transforms work in package.json on the module-deps
readme.
Source: https://github.com/substack/node-browserify#browserifytransform
Example (my_batman_project/node_modules/test_robin_module/package.json):
"browserify": {
"transform": [
"babelify"
]
},
browserify will read the configuration and perform any given transforms automatically.

I believe this issue is actually related to ESLint.
ESLint 2.0 changed what's required for it to interpret ES6 modules. http://eslint.org/docs/user-guide/migrating-to-2.0.0
You'll need to modify your ecmaFeatures configuration option and replace it with something like:
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},

Related

Enable global ESlint config

I want to make a eslint config works globally, so that I don't need to init it in each project.
then I installed eslint and some config extension globally.
npm install -g eslint eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks
And this is my eslint config file ~/.eslintrc.json
{
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": [
"airbnb-base"
],
"rules": {
}
}
But I got error when I lint my js file
ESLint couldn't find the config "airbnb-base" to extend from. Please check that the name of the config is correct.
The config "airbnb-base" was referenced from the config file in "/home/molly/.eslintrc.json".
This is my global installed packages, airbnb is there.
Did I miss something ? I don't want to install eslint-plugin** in each of project
Probably a bit late for you but I don't think you can install eslint plugins globally.
The way around that worked for me is to create a directory where all my projects go and inside that directory create a package.json (npm init -y) and install all the plugins in that directory npm i -D eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks
Bring your global .eslintrc file in that directory which will act like a root eslint config for all your projects that's inside that directory now.
Essentially, your directory tree should like the following now:
projects/
package.json
.eslintrc
node_modules/
...
my_cool_project/
...
my_cool_project2/
...
...

Webpack Error: configuration.module

I have an uncommon webpack error and I don't know how to fix it..
It has something to do with my configuration, but I don't know what it is. A schoolmate of mine can perfectly run webpack in the console with the same project.
Earlier I got the error:
PS E:\HTL\Projects\EasyWater\Software\Beispielprojekte\WebPack_Dummy> webpack
The CLI moved into a separate package: webpack-cli.
Please install 'webpack-cli' in addition to webpack itself to use the CLI.
-> When using npm: npm install webpack-cli -D
-> When using yarn: yarn add webpack-cli -D
then I installed the Webpack CLI globally and now finally I get the error:
PS E:\HTL\Projects\EasyWater\Software\Beispielprojekte\WebPack_Dummy> webpack
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.module has an unknown property 'loaders'. These properties are valid:
object { exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, defaultRules?, unknownContextCritical?, unknownContextRecursive?, unk
nownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp?, strictExportPresence?, strictThisContextOnImports? }
-> Options affecting the normal modules (`NormalModuleFactory`).
I have already reinstalled node js and literally everything, but I am continously get the same error.
As I said, my schoolmate can execute webpack with the same project.
I have installed:
ts-loader -g
webpack -g
webpack-cli -g
typescript -g
I suspect your friend is not using webpack 4 and you are using a webpack.config.js configuration file incompatible with webpack 4. I myself am walking through a tutorial involving webpack and encountered the same error. By uninstalling webpack 4 in favor of webpack 3 (npm install webpack#3 --save-dev), I was able to run my npm build script of webpack --config webpack.config.js without issue and without the need for webpack-cli. An update to the configuration file may be more appropriate, but I am just starting out with webpack and this is the path of least resistance.
When using Webpack v4, change the 'loaders' option into 'rules' e.g
module.exports = {
entry: './your-entry-file',
output: {
...
},
module:{
**rules**: [{
//rules replaces loaders
//all your configuration comes here
}]
}
}

Error: Couldn't find preset "es2015" relative to directory — Intellij Filewatcher

trying to set up a Filewatcher with Intellij in order to use ES6 with Babel transpiler. I have followed their guide here, which seemed to install fine except for when I try to write javascript code and it executes the transpiler code, I get this error:
Error: Couldn't find preset "es2015" relative to directory "/Volumes/ShanStore/Main/Projects/NewWebsite"
at /Users/Shan/node_modules/babel-core/lib/transformation/file/options/option-manager.js:281:17
at Array.map (native)
at OptionManager.resolvePresets (/Users/Shan/node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:20)
at OptionManager.mergePresets (/Users/Shan/node_modules/babel-core/lib/transformation/file/options/option-manager.js:254:10)
at OptionManager.mergeOptions (/Users/Shan/node_modules/babel-core/lib/transformation/file/options/option-manager.js:239:14)
at OptionManager.init (/Users/Shan/node_modules/babel-core/lib/transformation/file/options/option-manager.js:338:12)
at File.initOptions (/Users/Shan/node_modules/babel-core/lib/transformation/file/index.js:216:65)
at new File (/Users/Shan/node_modules/babel-core/lib/transformation/file/index.js:137:24)
at Pipeline.transform (/Users/Shan/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
at transform (/Users/Shan/node_modules/babel-cli/lib/babel/util.js:50:22)
I have Node v6.4.0 and npm 3.10.3 installed. I have a file named .babelrc in my root directory like so—
NewWebsite
|_ .babelrc
|_ index.html
|_ script.js
and I ran these commands to install babel related things:
sudo npm install --save-dev babel-cli
sudo npm install --save-dev babel-preset-es2015
My .babelrc file looks like this:
{
"presets": ["es2015"]
}
I've searched through the various solutions on here and none of them have worked. I have no idea what's wrong here! Any help?

Is it possible write a gulpfile in es6?

Question: How can I write my gulp file in ES6 so I can use import instead of require and use => syntax over function()?
I can use io.js or node any version.
gulpfile.js:
import gulp from "./node_modules/gulp/index.js";
gulp.task('hello-world', =>{
console.log('hello world');
});
Errors:
import gulp from "./node_modules/gulp/index.js";
^^^^^^
SyntaxError: Unexpected reserved word
gulp.task('hello-world', =>{
^^
SyntaxError: Unexpected token =>
Inside the node_modules/gulp/bin/gulp.js i've changed the first line to #!/usr/bin/env node --harmony as asked in this stack
Yes, you can by using babel.
Make sure you've got the latest version of the gulp-cli.
npm install -g gulp-cli
Install babel as a dependency of the project.
npm install --save-dev babel
Rename gulpfile.js to gulpfile.babel.js
Your gulpfile might look something like this:
import gulp from 'gulp';
gulp.task('default', () => {
// do something
});
Update for Babel 6.0+
As correctly pointed out by Eric Bronniman, there are a few extra steps involved in getting this to work with the latest version of babel. Here are those instructions:
Again, make sure you've got the latest version of gulp-cli
npm install -g gulp-cli
Then install gulp, babel core, and the es2015 presets
npm install --save-dev gulp babel-core babel-preset-es2015
Then, either add the following to a .babelrc file or to your package.json
"babel": {
"presets": [
"es2015"
]
}
Your gulpfile.js should be named gulpfile.babel.js
Note you can now use many/most ES6 features in Node.js v4.0.0 without babel. However apparently 'import' is still not supported. See: https://nodejs.org/en/docs/es6/
Edit: Most of the popular ES6 features (including destructuring and spread) are supported by default in NodeJS 5.0 (see above link.) The only major missing feature appears to be ES6 modules as far as I can tell.
If you have the latest versions of gulp & node, you can simply create a gulpfile as gulpfile.mjs instead of gulpfile.js and it should work without needing to use Babel or any other transpiler.
.mjs is a special format used by node which allows usage of ES Modules.
References :-
https://nodejs.org/api/esm.html#esm_enabling
https://nodejs.org/api/packages.html#packages_determining_module_system
Example :-
// Filename: gulpfile.mjs
import gulp from 'gulp';
export default task;
function task()
{
return (
gulp.src(`./src/js/**/*.js`)
.pipe(gulp.dest(`./dist/Static/js`)
);
}
I use babel-node and native gulp.
Install babel and gulp as devDependencies.
Write gulpfile.js with ES6 syntax.
Use command ./node_modules/.bin/babel-node ./node_modules/.bin/gulp to run gulp
In package.json scripts section, you can skip the first ./node_modules/.bin/ part - as babel-node ./node_modules/.bin/gulp.
The advantage of this appoach is, one day when the node.js support all ES6 features one day, all you need to opt-out babel runtime is to replace babel-node with node. That is all.
If you're using the most modern version of Gulp and the Gulp CLI, you can just do Gulpfile.babel.js and it will understand and transpile your ES6 gulpfile with BabelJS by default.
It is also important to have the BabelJS transpiler installed under devDependencies as is Gulp:
npm install --save-dev babel
Also note that to require gulp in this context, you do not have to import the index.js, you can just:
import gulp from 'gulp';
Basically, what you need to install using npm is gulp, gulp-babel and babel-resent-env, add "env" to your .babelrc presets array, and use a gulpfile.babel.js file.
npm install gulp-babel --save-dev
Some of the answers mentioned babel-core, babel-preset-es2015, etc. The Babel official setup guide with Gulp is to use gulp-babel only, while gulp-babel has dependencies modules including babel-core so you don't need to install it separately.
About preset, you need to use a preset to make Babel actually do something, which is called Preset Env that automatically determines the Babel plugins you need based on your supported environments.
npm install babel-preset-env --save-dev
and in .babelrc file
{
"presets": ["env"]
}
/*
* Steps
* 1. Rename your gulpfile.js to gulpfile.babel.js
* 2. Add babel to your package.json (npm install -D babel)
* 3. Start writing ES6 in your gulpfile!
*/
import gulp from 'gulp'; // ES6 imports!
import sass from 'gulp-sass';
const sassOpts = { outputStyle: 'compressed', errLogToConsole: true }; // "let" and "const"!!
gulp.task('sass', () = > { // Arrow functions!!
gulp.src('./**/*.scss')
.pipe(sass(sassOpts))
.pipe(gulp.dest('./'));
});
gulp.task('default', ['sass'], () => { // Arrow functions!!
gulp.watch('./src/sass/**/*.scss', ['sass'])
.on('change', (e) => { // Arrow functions!!
console.log(`File ${e.path} was ${e.type}, running Sass task...`); // Template strings and interpolation!!
});
});
Steps I followed for developing the code for gulpfile in es6:
npm install gulp && sudo npm install gulp -g.
Please make sure that you you are using the updated version of Gulp.
The current version at the time of writing this answer was 3.9.1. To check which version of gulp is installed, type gulp -v
npm install babel-core babel-preset-es2015-without-strict --save-dev
Type touch .babelrc in the terminal
In the .babelrc file, add this code
{
"presets": ["es2015-without-strict"]
}
Created the gulp config file with the name gulpfile.babel.js
Voila!!! You can now write the config code for gulp in ES6.
Source: Using ES6 with Gulp - Mark Goodyear
I have just had the same problem and
solved as following:
Windows 10
node version: 14.15.4
npm version: 6.14.10
gulp version: 4.0.2
using yarn v1
Renamed gulpfile.js as gulpfile.babel.js
Added these packages as devdependency:
"#babel/cli": "^7.12.10",
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"#babel/register": "^7.12.10",
"gulp-babel": "^8.0.0",
Added babel.config.json
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"ie": "10",
"edge": "17",
"firefox": "60",
"chrome": "70",
"safari": "11.1"
}
}
]
]
}
Finally I deleted yarn.lock file and node_modules folder and installed all packages.
yarn install
This is how my gulpfile.babel.js file looks like:
import { src, dest, parallel, series, watch } from 'gulp';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import concat from 'gulp-concat';
import postcss from 'gulp-postcss';
import replace from 'gulp-replace';
import sass from 'gulp-sass';
import { init, write } from 'gulp-sourcemaps';
import uglify from 'gulp-uglify';
import babel from "gulp-babel";
//....
const _default = series(
parallel(scssTask, jsTask),
cacheBustTask,
watchTask
);
export { _default as default };
Note:
yarn gulp command runs properly but I still have that warning:
Requiring external module #babel/register

requirejs, babelify and browserify when npm installing and building a module

I have a problem with an npm module I've created. It's built using browserify and babelify.
Here is a snippet from the package.json:
"name": "foo",
"main": "index.js",
"scripts": {
"start": "watchify src/foo.js -t babelify -s foo -o ./index.js"
}
Which is basically the entire build process (no minifying or anything). There are also some tests, which run without a problem.
In src/foo.js I import other files, which are located in the same folder.
import bar from './bar';
So, the file structure looks something like:
index.js
package.json
src/
foo.js
bar.js
Now, when I install the module elsewhere, in a completely different project, and import it:
import foo from 'foo';
... and build the new project with
watchify src/app.js -d -t babelify -o js/app.js
I get this error:
Error: Cannot find module './bar' from '[file_path]/node_modules/foo/'
So basically (as I understand it), it looks at the (now) var bar = require('./bar'); and searches in the file path (the same folder) whereas, everything in reality was bundled into one file, everything included.
What am I missing here? How do I build it correctly?

Categories