babel es5 to es6 converting less extension to css on imports - javascript

I wrote some npm scripts that builds the ./lib directory before publish to npm.
1. script is responsible to convert all es6 *.js files in ./src/components/ to es5 syntax and then copy the files to ./lib (same structure).
This is the script:
"cross-env NODE_ENV=production babel ./src/components --out-dir ./lib --ignore spec.js --copy-files"
And this is the .babelrc file:
{
"presets": [
"react",
"stage-1"
],
"env": {
"development": {
"presets": [
"latest",
"react-hmre"
]
},
"production": {
"presets": [
[
"latest",
"es2015"
]
],
"plugins": [
"transform-react-constant-elements",
"transform-react-remove-prop-types",
[
"transform-imports",
{
"react-bootstrap": {
"transform": "react-bootstrap/lib/${member}",
"preventFullImport": true
},
"lodash": {
"transform": "lodash/${member}",
"preventFullImport": true
}
}
]
]
},
"test": {
"presets": [
"latest"
]
}
}
}
I have another script that responsible to convert .less files to .css and copy them to ./lib (same structure):
"lessc-glob ./src/components/**/*.less lib"
Everything works well as expected, but i have one problem now. The import that i have inside the .js files are referring to .less files, but i need it to change to .css extensions.
To make things clear,
What i have now is:
import css from './styles.less';
Converted into this:
var _styles = require('./styles.less');
But i want it to convert to this:
var _styles = require('./styles.css');

replace can be installed and utilized to find instances of .less and replace them with .css in your resultant ES5 .js file/s.
npm script
Add a replace script to your package.json as follows:
...
"scripts": {
...
"replace": "replace \".less\" \".css\" ./lib/components/ -r --include=\"*.js\""
},
...
A call to the replace script can then be chained to the end your script that is responsible for converting all es6 *.js files. E.g.
...
"scripts": {
...
"quux": "cross-env NODE_ENV=production babel ./src/components --out-dir ./lib --ignore spec.js --copy-files && npm run replace",
"replace": "replace \".less\" \".css\" ./lib/components/ -r --include=\"*.js\""
...
},
...
Note the && npm run replace part added to the end of your current quux script.
I've assumed the components folder is copied to the lib folder too. If it's not then the ./lib/components/ part in the replace script will need to be changed to ./lib/.

Related

How to ignore files with #swc/cli?

I am using swc to transpile my Typescript code on a side project and am struggling ignoring the tests files from the final output using the cli --ignore option.
lib versions:
#swc/cli: ^0.1.57
#swc/core: ^1.2.173
command:
swc ./src --out-dir dist --ignore **/*.test.ts
.swrc config
{
"jsc": {
"target": "es5",
"paths": {
"#src/*": ["./src/*"]
},
"parser": {
"syntax": "typescript",
"decorators": true,
"dynamicImport": true
}
},
"minify": true,
}
I still saw all tests files in my dist output folder. Note that using the exclude property in the .swcrc like this "exclude": [".*\\.spec|test\\.(j|t)s$", "mocks", "types"] works, but how is the --ignore arg supposed to be used ?

How to remove unused imports with a command?

I have files in my nx project with import declaration without any use and I want to remove them.
After I searched in stackoverflow I found the answer to open the file in vscode, and press alt+shift+o and when the declaration is not used then it's remove and sort the import.
But I have 10,000 files. so is there a command to do that in all those files? I looking in eslint but there is no rule for that.
Install the no-unused-imports plugin
Add unused-imports to the plugins section of your .eslintrc file
{
"plugins": ["...", "unused-imports"]
}
add the following rules
"no-unused-vars": "off",
"unused-imports/no-unused-imports": "error",
"unused-imports/no-unused-vars": [
"warn",
{ "vars": "all", "varsIgnorePattern": "^_", "args": "after-used", "argsIgnorePattern": "^_" }
],
Then add script to your package.json file
"scripts": {
...
"fix-lint-errors": "eslint nx --fix"
},
from command line run the script
npm run fix-lint-errors
or
yarn fix-lint-errors
If you are a heavy vscode user, so you can simply open your preference settings then add the following to your settings.json:
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
Or you can make a stand alone tslint file that has the following in it:
{
"extends": ["tslint-etc"],
"rules": {
"no-unsed-declaration: true"
}}
Then run the following command to fix the imports:
tslint --config tslint-imports.json --fix --project
Then use
ng build
or
ng build name_of_project --configuration=production

ESLint define folder in config file. (Ignore all but..., Include only...)

How to set the folder to lint in the .eslintrc.json file, instead after the eslint command in package.json.
package.json (snippet)
"scripts: {
"lint": "eslint ./src --ext .js,.jsx,.ts,.tsx",
}
I want only:
"scripts: {
"lint": "eslint",
}
and define the path and ext in the .eslintrc.json.
Alternativ, set .eslintignore to ignore ALL but not ./src.
I only want to lint the src-folder. Not the root.
Also for the eslint plugin of vscode.
My current solution:
.eslintignore
/*
!/src
But I wondering, why is there no option in the config files to set the folder/s to lint.
I'm looking for the most common and elegant solution.
Maybe it sounds like a duplicate here. But I searched a lot of topics and found nothing similar to solve my problem.
Set in overrides inside .eslintrc.json
If you specified directories with CLI (e.g., eslint lib), ESLint searches target files in the directory to lint. The target files are *.js or the files that match any of overrides entries (but exclude entries that are any of files end with *).
{
"rules": {
"quotes": ["error", "double"]
},
"overrides": [
{
"files": ["bin/*.js", "lib/*.js"],
"excludedFiles": "*.test.js",
"rules": {
"quotes": ["error", "single"]
}
}
]
}
Refer: document of Configuring ESLint
I've adapted your solution with the .eslintignore file and put the rules directly into my config file's ignorePatterns option (.eslintrc.cjs in my case). Works like a charm for me:
module.exports = {
ignorePatterns: ['/*', '!/src']
[...]
}
In addition to #billythetalented's comment I had to add a dot in the package.json:
"scripts": {
"lint": "eslint .",
...
}
Otherwise, It didn't lint anything

Setting up Webpack with Babel for ES6 coding [duplicate]

How to use ES6 in webpack.config ?
Like this repo
https://github.com/kriasoft/react-starter-kit
does ?
For instance:
using this
import webpack from 'webpack';
instead of
var webpack = require('webpack');
It is quite a curiosity rather than a need.
Try naming your config as webpack.config.babel.js. You should have babel-register included in the project. Example at react-router-bootstrap.
Webpack relies on interpret internally to make this work.
As an alternative to what #bebraw suggests, you can create a JavaScript automation script with ES6+ syntax:
// tools/bundle.js
import webpack from 'webpack';
import webpackConfig from './webpack.config.js'; // <-- Contains ES6+
const bundler = webpack(webpackConfig);
bundler.run(...);
And execute it with babel:
$ babel-node tools/bundle
P.S.: Calling webpack via JavaScript API might be a better approach (than by calling it via a command line) when you need to implement more complex build steps. E.g. after server-side bundle is ready, startup Node.js app server, and right after Node.js server is started, launch BrowserSync dev server.
See also:
React Starter Kit (package.json/scripts, tools/bundle.js, tools/webpack.config.js)
React Static Boilerplate (run.js, webpack.config.js, node run)
You might not need Gulp.js
Another approach is to have a npm script like this: "webpack": "babel-node ./node_modules/webpack/bin/webpack", and run it like so: npm run webpack.
This is what worked for me using webpack 4:
In package.json:
"scripts": {
"dev": "cross-env APP_ENV=dev webpack-serve --require #babel/register"
},
"devDependencies": {
"#babel/core": "^7.0.0-rc.1",
"#babel/register": "^7.0.0-rc.1",
"#babel/preset-env": "^7.0.0-rc.1",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2"
},
"babel": {
"presets": [
["#babel/preset-env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"transform-es2015-modules-commonjs"
]
}
You can clearly see how each dependency is used, so no surprises there.
Note I am using webpack-serve--require, but if you want to use the webpack command instead, replace it with webpack --config-register. In either case, #babel/register is needed to make this work.
And that's it!
yarn dev
And you are able to use es6 in the config!
For webpack-dev-server, use the --config-register option which is the same as with the webpack command
NOTE:
NO need to rename the config file to webpack.config.babel.js (as suggested by the accepted answer). webpack.config.js will work just fine.
I had a problem getting #Juho's solution running with Webpack 2. The Webpack migration docs suggest you to turn of babel module parsing:
It is important to note that you will want to tell Babel to not parse
these module symbols so webpack can use them. You can do this by
setting the following in your .babelrc or babel-loader options.
.babelrc:
{
"presets": [
["es2015", { "modules": false }]
]
}
Sadly, this conflicts with the automatic babel register functionality. Removing
{ "modules": false }
from the babel config got things running again. However, this would result in breaking tree-shaking, so a complete solution would involve overwriting the presets in the loader options:
module: {
rules: [
{
test: /\.js$/,
include: path.resolve('src'),
loader: 'babel-loader',
options: {
babelrc: false,
presets: [['env', {modules: false}]]
}
}
]
}
Edit, 13th Nov 2017; updated webpack config snippet to Webpack 3 (thanks to #x-yuri). Old, Webpack 2 snippet:
{
test: /\.js$/,
exclude: ['node_modules'],
loader: 'babel',
query: {
babelrc: false,
presets: [
['es2015', { modules: false }],
],
},
},
This is really easy, but it wasn't obvious to me from any of the answers, so if anyone else is confused like me:
Just append .babel to the part of your filename before the extension (assuming that you have babel-register installed as a dependency).
Example:
mv webpack.config.js webpack.config.babel.js
Configuration for Babel 7 & Webpack 4
package.json
...
"scripts": {
"start": "webpack-dev-server --env.dev",
"build": "webpack --env.prod",
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.0.0",
"#babel/plugin-proposal-class-properties": "^7.0.0",
"#babel/preset-env": "^7.0.0",
"#babel/preset-react": "^7.0.0",
"#babel/register": "^7.0.0",
"babel-loader": "^8.0.0",
...
"webpack": "^4.17.2",
"webpack-cli": "^3.1.0",
"webpack-config-utils": "^2.3.1",
"webpack-dev-server": "^3.1.8"
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
webpack.config.babel.js
import webpack from 'webpack';
import { resolve } from 'path';
import { getIfUtils, removeEmpty } from 'webpack-config-utils';
export default env => {
const { ifProd, ifNotProd } = getIfUtils(env);
return {
mode: ifProd('production', 'development'),
devtool: ifNotProd('cheap-module-source-map'),
output: {
path: resolve(__dirname, ifProd('prod', 'dev')),
filename: 'bundle.js'
},
For TypeScript: straight from https://webpack.js.org/configuration/configuration-languages/
npm install --save-dev typescript ts-node #types/node #types/webpack
# and, if using webpack-dev-server
npm install --save-dev #types/webpack-dev-server
then proceed to write your, e.g.:
webpack.config.ts
import path from 'path';
import webpack from 'webpack';
const config: webpack.Configuration = {
mode: 'production',
entry: './foo.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'foo.bundle.js'
}
};
export default config;
Check the link for more details where you can use a plugin to have a separate tsconfig file just for the webpack config if you're not targeting commonjs (which is a req for this to work since it relies on ts-node).
For readers in 2022:
"webpack": "^5.70.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
Add "type": "module" in package.json
Change the syntax of your webpack.config.js to ESM.
Enjoy.
One more way is to use require argument for node:
node -r babel-register ./node_modules/webpack/bin/webpack
Found this way in electron-react-boilerplate, look at build-main and build-renderer scripts.
Rename webpack.config.js to webpack.config.babel.js.
Then in .babelrc: {"presets": ["es2015"]}
However, if you want to use a different babel config for babel-cli, your .babelrc might look something like this:
{
"env": {
"babel-cli": {
"presets": [["es2015", {"modules": false}]]
},
"production": {
"presets": ["es2015"]
},
"development": {
"presets": ["es2015"]
}
}
}
And in package.json:
{
"scripts": {
"babel": "BABEL_ENV='babel-cli' babel src -d dist/babel --source-maps",
"build-dev": "NODE_ENV='development' webpack -d --progress --profile --colors",
...
},
...
}
It's dumb but the {"modules": false} will break webpack if you don't use different envs.
For more info about .babelrc, check the official docs.
Don't have enough rep to comment, but I wanted to add for any TypeScript users out there a similar solution to #Sandrik above
I have two scripts that I use pointing to webpack configs (JS files) that contain ES6 syntax.
"start-dev": "./node_modules/.bin/ts-node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js --config ./webpack/webpack.config.dev.js"
and
"build": "./node_modules/.bin/ts-node ./node_modules/webpack/bin/webpack.js --config webpack/webpack.config.js"
Using Webpack 4 and Babel 7
To setup a webpack configuration file to use ES2015 requires Babel:
Install dev dependencies:
npm i -D webpack \
webpack-cli \
webpack-dev-server \
#babel/core \
#babel/register \
#babel/preset-env
npm i -D html-webpack-plugin
Create a .babelrc file:
{
"presets": ["#babel/preset-env"]
}
Create your webpack config, webpack.config.babel.js:
import { resolve as _resolve } from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const config = {
mode: 'development',
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'src/index.html'
})
],
resolve: {
modules: [_resolve(__dirname, './src'), 'node_modules']
}
};
export default config;
Create your scripts in package.json:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack-dev-server --open"
},
Run npm run build and npm start.
The webpack config is based on a sample project with the following directory structure:
├── README.md
├── package-lock.json
├── package.json
├── src
│   ├── Greeter.js
│   ├── index.html
│   └── index.js
└── webpack.config.babel.js
Sample project: Webpack Configuration Language Using Babel
My Best approach along with npm script is
node -r babel-register ./node_modules/webpack/bin/webpack
and configure rest of scripts as per your requirement for Babel
After tons of the documents...
Just install es2015 preset (not env !!!) and add it to
.babelrc:
{
"presets": [
["es2015", { "modules": false }]
]
}
Rename your webpack.config.js to webpack.config.babel.js
Adding es6 to webpack is a 3 step process
In webpack.config.js add
module:{
rules:[
{
test: /\.js$/,
loader: 'babel-loader'
}
]
}
Create a .babel.rc and add inside it
{
"presets": ["#babel/env", "#babel/react"],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
]
]
}
in package.json add
npm install #babel/core --save-dev
npm install #babel/preset-env --save-dev
npm install #babel/preset-react --save-dev
npm install #babel/plugin-proposal-class-properties --save-dev
npm install babel-loader --save-dev
Edit: Works as of Feb 2021
https://github.com/webpack/webpack-cli/pull/2381
You can't. You have to convert it to CommonJS, either with babel or esm.
https://github.com/webpack/webpack-cli/issues/282
But you can run webpack -r esm #babel/register

Grunt + Babel successfully runs but doesn't do anything

I'm rather new to grunt/npm but after reading up the docs. I have made myself a package.json and a Gruntfile.js. Here's my folder structure:
/
|- src
|- myfile.es6
|- anotherfile.es6
|- etc.
|- Gruntfile.js
|- package.json
What I have
Here's my Gruntfile:
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
babel: {
options: {
sourceMap: true,
plugins: ['es2015']
},
dist: {
files: [{
expand: true,
cwd: 'src/',
src: ['*.es6'],
dest: 'dist/',
ext: '.js'
}]
}
}
});
grunt.registerTask('default', ['babel'])
};
And then here's my package.json:
{
"name": "Cheddar",
"version": "0.2.0",
"devDependencies": {
"babel-preset-es2015": "^6.6.0",
"grunt": "^1.0.1",
"grunt-babel": "^6.0.0"
},
"scripts": {
"test": "grunt --verbose"
}
}
What does it do?
I have my src/ folder which contains my source files (*.es6). I want to transpile these to a dist/ directory with grunt.
What I've tried
Then I installed all the dependencies / babel-cli / grunt-cli/ etc. with npm install and npm-update --save
Seems good, so I went ahead and ran grunt:
$ grunt
Running "babel:dist" (babel) task
Done.
$ ls
Gruntfile.js node_modules/ package.json src/
The ls is outputting the exact same thing as before I ran grunt. So nothing is appearing to happen. Where's my output dist? This has been bugging me for the past few hours. I've tried installing babelify, and quite a few other fixes from blogs across the internet but alas, nothing works.
Try using the keyword "presets" instead of "plugins":
babel: {
options: {
sourceMap: true,
presets: ['es2015']
}
...
}
When I use your configuration, grunt seems to error out because it can't find the plugin called "es2015". Everything worked after I made that change.
Try a more literal example from the README like:
grunt.initConfig({
babel: {
options: {
sourceMap: true,
presets: ['es2015']
},
dist: {
files: {
'dist/myfile.js': 'src/myfile.es6'
}
}
} });
After you get that working try specifying *.es6 etc. under files. If you look at the source for the grunt-babel plugin it may be more limited than one would assume.
You can also just use npm scripts and specify the babel command line directly which I feel is simpler than using grunt.

Categories

Resources