I am using Grunt to build a React project and I want to have 'dev' and 'prod' flavours. As react docs says:
To use React in production mode, set the environment variable NODE_ENV to production.
A minifier that performs dead-code elimination such as UglifyJS is
recommended to completely remove the extra code present in development mode.
I am very new using grunt, browserify and stuff but let's see. First problem I have is with envify, I use it as a transform:
browserify: {
options: {
transform: ['reactify'],
extensions: ['.jsx']
},
dev:{
options: {
watch: true //Uses watchify (faster)
},
src: ['js/app.js'],
dest: 'js/bundle.js'
},
/**
* To use React in production mode, set the environment variable NODE_ENV to production.
* A minifier that performs dead-code elimination such as UglifyJS is
* recommended to completely remove the extra code present in development mode.
**/
prod: {
options: {
transform: ['envify'] //How to set up NOD_ENV='production' ?
},
src: ['js/app.js'],
dest: 'js/bundle.js'
}
},
Ok, doing grunt:dev works just fine. So when running grunt:prod... How can I set NODE_ENV: 'production'? I mean, I know I am passing 'envify' as a transform but... No idea how to use that.
After this, I also have an uglify task:
uglify: {
prod: {
files: {
'js/bundle.min.js': ['js/bundle.js']
}
}
}
So after calling grunt:prod, what it creates is two files (bundle.js and bundle-min.js). In production I will like to only have bundle.min.js. I know I can do:
js/bundle.js': ['js/bundle.js']
But mmm I don't know if there is a way to just rename it to bundle.min.js, I guess so... the problem is that in the html I have:
<script src="js/bundle.js"></script>
Is there here also a trick to make it accepts either bundle.js or bundle.min.js?
Thanks in advance.
Transforms are local, and well made packages put their transforms in their package.json file. Unless you're using envify in your own code, you don't need to do anything with it.
What you do need is grunt-env, or another way to set environmental variables.
Here's an alternative by using package.json:
{
"scripts": {
"build": "NODE_ENV=development grunt build-dev",
"dist": "NODE_ENV=production grunt dist"
}
},
"devDependencies": {
"grunt": "...",
"grunt-cli": "..."
}
The benefit here is that the person using your package doesn't even need to install grunt globally. npm run build will run ./node_modules/.bin/grunt build-dev with the correct environmental variable set.
Both John Reilly's and FakeRainBrigand 's answers did not work for me. What worked for me was the following:
Step 1 - Run this command where your package.json is
npm i grunt-env --save-dev
Step 2 - Add the code in "evn:" to your Gruntfile.js within grunt.initConfig like so:
grunt.initConfig({
...
env: {
prod: {
NODE_ENV: 'production'
}
},
...
});
Step 3 - Add the grunt task to your Gruntfile.js
grunt.loadNpmTasks('grunt-env');
Step 4 - Call it before browserify like so:
grunt.registerTask("default", ["env", "browserify"]);
Just an addition to the great answer by FakeRainBrigand, if you're running on Windows (like me) then you need a subtly different syntax in your scripts section:
{
"scripts": {
"build": "SET NODE_ENV=development&&grunt build-dev",
"dist": "SET NODE_ENV=production&&grunt dist"
}
},
"devDependencies": {
"grunt": "...",
"grunt-cli": "..."
}
Related
I want to run some stuff only once before all test cases. Therefore, I have created a global function and specified the globalSetup field in the jest configuration:
globalSetup: path.resolve(srcPath, 'TestUtils', 'globalSetup.ts'),
However, within globalSetup, I use some aliases # and Jest complains it does not find them.
How can I run globalSetup once the aliases have been sorted out?
My Jest configuration is as follows:
module.exports = {
rootDir: rootPath,
coveragePathIgnorePatterns: ['/node_modules/'],
preset: 'ts-jest',
setupFiles: [path.resolve(__dirname, 'env.testing.ts')],
setupFilesAfterEnv: [path.resolve(srcPath, 'TestUtils', 'testSetup.ts')],
globalSetup: path.resolve(srcPath, 'TestUtils', 'globalSetup.ts'),
globals: {},
testEnvironment: 'node',
moduleFileExtensions: ['js', 'ts', 'json'],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' })
};
When I run testSetup before every test, it runs ok the aliases, but this does not happen with globalSetup.
Any clue what could I do?
I managed to get this work by including tsconfig-paths/register at the top of my globalSetup file:
// myGlobalSetupFile.ts
import 'tsconfig-paths/register';
import { Thing } from './place-with-aliases';
export default async () => {
await Thing.doGlobalSetup();
}
You have to make sure you have tsconfig-paths installed in your project.
Unfortunately I have found there is no solution for this based on the comments on this issue:
https://github.com/facebook/jest/issues/6048
The summary is that globalSetup runs outside of Jest ecosystem and therefore it will not recognize the aliases, etc.
There are several workarounds, for example, if your npm run test command is something like this:
"test": "jest --config config/jest.config.js --detectOpenHandles --forceExit"
Then you can do something like:
"test": "node whateverBeforeJest.js && jest --config config/jest.config.js --detectOpenHandles --forceExit"
I am new in using Eslint.
So far I have installed Eslint in my local project and configured it. The eslintrc.js file contains
module.exports = {
env: {
node: true,
commonjs: true,
es6: true,
mocha: true,
},
extends: [
'airbnb-base',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parserOptions: {
ecmaVersion: 2018,
},
rules: {
},
};
And in package.json I have
"scripts": {
"lint": "eslint .eslintrc.js --fix",
}
In terminal I run
npm run lint
And the output is
> apigateway#1.0.0 lint C:\nodeprojects\restapi
> eslint .eslintrc.js --fix
C:\nodeprojects\restapi\.eslintrc.js
0:0 warning File ignored by default. Use a negated ignore pattern (like "--ignore-pattern '!<relative/path/to/filename>'") to override
But if I run
eslint <foldername> --fix then it works.
I am using webstorm IDE and in windows os.
Any help is highly appreciated.
ESlint default behaviour is ignoring file/folders starting with . - https://github.com/eslint/eslint/issues/10341.
In case for example you want to lint .storybook folder, ESLint will ignore it by default. To lint it, .eslintrc.js must include:
{
...
// Lint ".storybook" folder (don't ignore it)
"ignorePatterns": ["!.storybook"],
...
}
Because of that default ESLint behaviour, I do in all my projects like this (lint whole project from the root) :
{
...
// ESlint default behaviour ignores file/folders starting with "." - https://github.com/eslint/eslint/issues/10341
"ignorePatterns": ["!.*", "dist", "node_modules"],
...
}
Where I first don't ignore any file/folder starting with . and then I exclude folders that I actually want to ignore.
Your npm script runs the linter on the .eslintrc.js file and this file is as the comment says File ignored by default.
You need to change the lint script from:
"lint": "eslint .eslintrc.js --fix",
to:
"lint": "eslint <foldername> --fix"
Where <foldername> is the correct folder.
I ran into this issue where the pre-commit Husky hook would try to scan this file when trying to commit merges (where someone changed .eslintrc.js previously), then this would fail the merge commit in team members' local envs (file ignored by default)
You can create a .eslintignore file next to .eslintrc.js. Then in .eslintignore put:
!.eslintrc.js
I am trying to build a different bundle based on an argument passed to webpack.
I have a create-react-app that I have ejected from and currently currently if I do npm run build it builds a bundle using webpack. As I have both an english and spanish version of the site I was hoping that I could pass an argument here. i.e. to build a Spanish version something like npm run build:es.
My webpack file currently just builds the English bundle. There is a separate process during the application to pull in translations, but during the building of the bundle it would be great if I could stipulate which language to build the bundle for.
Anyone have any ideas.
The relevant webpack code is below:
//default messages for translations
var defaultMessages = require('/translations/en.json');
//more webpack stuff......
{
test: /\.(js|jsx)$/,
loader: require.resolve('string-replace-loader'),
query: {
multiple: Object.keys(defaultMessages).map(key => ({
search: `__${key}__`,
replace: defaultMessages[key]
}))
}
},
Webpack can receive a --env argument, which is then passed to the webpack.config file. The key is to export a function returning the configuration from your webpack.config.js, not the raw configuration.
$ webpack --env=lang_es
And in webpack.config.js:
module.exports = function(env) {
if (env === 'lang_es') {
// ...
}
return {
module: {
// ...
},
entry: {
// ...
}
}
}
And in package.json:
"scripts": {
"build_es": "webpack --env=lang_es",
}
This was originally really meant to distinguish between build types, e.g. development or production, but it's just a string passed into the config file - you can give it any meaning you want.
As hinted in the comments, using environment variables is the second, webpack-independent, approach. You can set the environment variable directly in package.json's scripts section:
"scripts": {
"build_es": "BUILD_LANG=es webpack",
}
(Use cross-env to set the environment when developing on Windows).
And in webpack.config.js:
if (process.env.BUILD_LANG === 'es') {
// ...
}
This environment-based approach has been used in a few places already (for example Babel's BABEL_ENV variable), so I'd say that it has gathered enough mileage to consider it proven and tested.
Edit: fixed the cross-env part to mention that it's only necessary on Windows.
Recently, we've upgraded to ESLint 3.0.0 and started to receive the following message running the grunt eslint task:
> $ grunt eslint
Running "eslint:files" (eslint) task
Warning: No ESLint configuration found. Use --force to continue.
Here is the grunt-eslint configuration:
var lintTargets = [
"<%= app.src %>/**/*/!(*test|swfobject)+(.js)",
"test/e2e/**/*/*.js",
"!test/e2e/db/models/*.js"
];
module.exports.tasks = {
eslint: {
files: {
options: {
config: 'eslint.json',
fix: true,
rulesdir: ['eslint_rules']
},
src: lintTargets
}
}
};
What should we do to fix the error?
The error you are facing is because your configuration is not present.
To configure the eslint type
eslint --init
then configure as your requirement.
then execute the project again.
I've had the same error. It seems to need configuration.
Go to your project root & run in terminal
./node_modules/.bin/eslint --init
Try to swap config with configFile. Then :
Create eslint.json file and
Point the right location of it (relative to Gruntfile.js file)
Place some configuration in that file (eslint.json), i.e.:
.
{
"rules": {
"eqeqeq": "off",
"curly": "warn",
"quotes": ["warn", "double"]
}
}
for more examples, go here.
I hade the same problem with Gulp and running "gulp-eslint": "^3.0.1" version.
I had to rename config: to configFile in Gulp task
.pipe(lint({configFile: 'eslint.json'}))
For those having the same problem, this is how we've fixed it.
Following the Requiring Configuration to Run migration procedure, we had to rename eslint.json to .eslintrc.json which is one of the default ESLint config file names now.
We've also removed the config grunt-eslint option.
Create a new file on the root directory called .eslintrc.json file:
{
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"rules": {
"semi": "error"
}
}
Just follow the steps
1.create eslint config file name eslintrc.json
2.place the code as given below
gulp.src(jsFiles)
// eslint() attaches the lint output to the "eslint" property
// of the file object so it can be used by other modules.
.pipe(eslint({configFile: 'eslintrc.json'}))
// eslint.format() outputs the lint results to the console.
// Alternatively use eslint.formatEach() (see Docs).
.pipe(eslint.format())
// To have the process exit with an error code (1) on
// lint error, return the stream and pipe to failAfterError last.
.pipe(eslint.failAfterError());
Webpack
I had eslint.rc file in my root project directory but event though
I was getting error.
Solution was to add exclude property to "eslint-loader" rule config:
module.exports = {
// ...
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
// eslint options (if necessary)
}
},
],
},
// ...
}
We faced this problem today and realized, that the issue was not caused inside the project that we were working on, but inside a package that we had a link on using the command:
yarn link
Which is a feature often useful to test out new features or when trying to debug an issue in a package that manifests itself in another project.
We solved it by either removing the link, or in case of ember.js disabling the developer mode of our addon package.
index.js
module.exports = {
isDevelopingAddon: function() {
return false;
},
...
}
gulp.task('eslint',function(){
return gulp.src(['src/*.js'])
.pipe(eslint())
.pipe(eslint.format())
});
`touch .eslintrc` instead of .eslint
these two steps may help you!
Run the command ember init.
When it asks for overwriting the existing file(s). Type n to skipping overwriting the file.
Now it will automatically create required files like .eslintrc, etc.
For me the same issue occurred when i copied my folder except dist, dist_production and node_modules folder to another system and tried running ember build.
I'm trying to integrate my existing test processes to now include React, but am struggling on the code coverage part. I've been able to get my unit tests working fine by following this project/tutorial - https://github.com/danvk/mocha-react - http://www.hammerlab.org/2015/02/14/testing-react-web-apps-with-mocha/
I've been using Istanbul to cover my node code and it's working pretty well. However, I'm having trouble getting it to cover the jsx files that I'm using in my tests.
Here's an example of an existing Istanbul task, which also runs fine on vanilla js (node backend code)
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
gulp.task('test-api', function (cb) {
gulp.src(['api/**/*.js'])
.pipe(istanbul()) // Covering files
.pipe(istanbul.hookRequire()) // Force `require` to return covered files
.on('finish', function () {
gulp.src(['test/api/*.js'])
.pipe(mocha())
.pipe(istanbul.writeReports()) // Creating the reports after tests runned
.on('end', cb);
My issue ( i think ) is I can't get Istanbul to recognize the jsx files or they're not being compared to what was run in the tests. I tried using the gulp-react module to precompile the jsx to js so it can be used by Istanbul, but I'm not sure if it's working. It's not being covered somehow and I'm not sure where the issue is.
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var react = require('gulp-react');
gulp.task('test-site-example', function (cb) {
gulp.src(["site/jsx/*.jsx"]) //Nothing is being reported by Istanbul (not being picked up)
.pipe(react()) //converts the jsx to js and I think pipes the output to Istanbul
.pipe(istanbul())
.pipe(istanbul.hookRequire()) // Force `require` to return covered files
.on('finish', function () {
gulp.src(['test/site/jsx/*.js'], { //tests run fine in mocha, but nothing being shown as reported by mocha (not covered)
read: false
})
.pipe(mocha({
reporter: 'spec'
}))
.pipe(istanbul.writeReports())
.on('end', cb);
});
;
});
Any ideas what I'm doing wrong? Or any clue on how to integrate a test runner (preferably Istanbul) into a Gulp-Mocha-React project?
Add a .istanbul.yml file to your app root and add .jsx to extensions "extension"...
Here is what I did.
// File .istanbul.yml
instrumentation:
root: .
extensions: ['.js', '.jsx']
To kickstart istanbul and mocha with jsx
$ istanbul test _mocha -- test/**/* --recursive --compilers js:babel/register
This will convert your .jsx files to .js and then istanbul will cover them.
I hope this helps. It worked for me.
There is a library you can take a look at, gulp-jsx-coverage (https://github.com/zordius/gulp-jsx-coverage).
In case someone else is having the same problem and solutions above don't work, I found that adding a simple "-e .jsx" tag worked:
"scripts": {
"start": "meteor run",
"test": "NODE_ENV=test mocha --recursive --compilers js:babel-register --require tests/index.js ./tests/**/*.test.js",
"coverage": "NODE_ENV=test nyc -all -e .jsx npm test"
}
This solution was found at: http://www.2devs1stack.com/react/tape/testing/nyc/coverage/2016/03/05/simple-code-coverage-with-nyc.html
A great tutorial can be found at https://istanbul.js.org/docs/tutorials/es2015/
I just slightly modified it to include react. (I also used 'env' instead of 'es2015', but either should work.) Here are my configurations:
npm i babel-cli babel-register babel-plugin-istanbul babel-preset-env babel-preset-react cross-env mocha nyc --save-dev
.babelrc
{
"presets": ["env", "react"],
"env": {
"test": {
"plugins": [
"istanbul"
]
}
}
}
package.json
"scripts": {
"test": "cross-env NODE_ENV=test nyc mocha test/**/*.spec.js --compilers js:babel-register"
}
"nyc": {
"require": [
"babel-register"
],
"reporter": [
"lcov",
"text"
],
"sourceMap": false,
"instrument": false
}