How to build everything into a dist with folder structure by webpack? - apache

I am a java developer for years and just new to the js world. This question sounds stupid but I don't know what's the proper/best way to build a dist for reactjs app for deploying to production(nginx/apache).
From my understanding, the dist just like simple web app and should looks like
contains:
index.html
client.js (bundled js after compiled)
static files, e.g.
images, css, js libraries, etc
I follow the guide on:
https://github.com/learncodeacademy/react-js-tutorials/tree/master/1-basic-react
and have a simple web app(maybe this is not called web app) running by:
npm run dev
it uses webpack to bundles the client.js.min and deploy to a embedded web server by node(maybe i am wrong).
Question:
How to build all the things by a command, say "npm run build" and it should built everything in a folder called "dist". So I can deploy it to web server root by copying every in dist to the web root.
package.json
{
"name": "react-tutorials",
"version": "0.0.0",
"description": "",
"main": "webpack.config.js",
"dependencies": {
"babel-core": "^6.17.0",
"babel-loader": "^6.2.0",
"babel-plugin-add-module-exports": "^0.1.2",
"babel-plugin-react-html-attrs": "^2.0.0",
"babel-plugin-transform-class-properties": "^6.3.13",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-stage-0": "^6.3.13",
"react": "^0.14.6",
"react-dom": "^0.14.6",
"webpack": "^1.12.9",
"webpack-dev-server": "^1.14.1"
},
"devDependencies": {},
"scripts": {
"dev": "webpack-dev-server --content-base src --inline --hot",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
webpack.config.js
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : false,
entry: "./js/client.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
}
}
]
},
output: {
path: __dirname + "/src/",
filename: "client.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};

In your scripts dictionary of package.json add the following
"build" : "NODE_ENV='production' && node_modules/.bin/webpack -p"
This will tell webpack to read the config file and build it in production mode i.e minify etc etc. The -p flag does it. The node env is to ensure that production build are used for react and other libraries and to set an env variable of production for NODE_Env
To run type. npm run build

Related

npm script doesn't not launch karma test correctly

I'm using parcel to build my project on windows , and installed karma as my test runner. I hope when I changed my source code the parcel would rebuild the project and the karma would execute the test.so I add
"script": {
"dev-test": "parcel watch test/* --no-cache & karma start --auto-watch"
}
to my package.json.
The weird thing is when I run "npm run dev-test" , the parcel build the project but karma didn't excute any test, terminal shows "√ Built in 5.95s.", that's all I got.
I have to type the whole command "parcel watch test/* --no-cache & npx karma start --auto-watch" in my command line line(karma isn't installed globally so I have to add npx), it seems to be a workaround, but still have a bug("&" means parcel and karma runs simultaneously so karma would run the test several times when parcel is building project)
I don't want to type the whole command , I hope I can use npm script.
here's my package.json if it helps
{
"name": "custom-vue-component",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "parcel build test/* --no-cache --no-minify && karma start --single-run",
"dev-test": "parcel watch test/* --no-cache & karma start --auto-watch"
},
"repository": {
"type": "git",
},
"author": "me",
"license": "ISC",
"dependencies": {
"vue": "^2.6.11",
"vue-hot-reload-api": "^2.3.4"
},
"devDependencies": {
"#vue/component-compiler-utils": "^3.1.2",
"chai": "^4.2.0",
"chai-spies": "^1.0.0",
"karma": "^5.0.9",
"karma-chai": "^0.1.0",
"karma-chai-spies": "^0.1.4",
"karma-chrome-launcher": "^3.1.0",
"karma-mocha": "^2.0.1",
"karma-sinon-chai": "^2.0.2",
"mocha": "^7.2.0",
"parcel-bundler": "^1.12.4",
"sass": "^1.26.7",
"sinon": "^9.0.2",
"sinon-chai": "^3.5.0",
"vue-template-compiler": "^2.6.11"
},
"alias": {
"vue": "./node_modules/vue/dist/vue.common.js"
}
}
and karma.conf.js
module.exports = function(config) {
config.set({
basePath: "",
frameworks: ["mocha", "sinon-chai"],
client: {
chai: {
includeStack: true,
},
},
files: ["dist/**/*.test.js", "dist/**/*.test.css"],
exclude: [],
preprocessors: {},
reporters: ["progress"],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ["ChromeHeadless"],
singleRun: false,
concurrency: Infinity,
});
}
If you are Windows user, you maybe meet this problem.
You can solve it by run parcel watch test/* --no-cache & karma start separately:
Open a git bush window and run npx parcel watch test/* --no-cache
Open another git bush window and run npx karma start

mocha cannot compile ES6, even with correct options

I'd like to run mocha on a test directory. My tests are written in ES6, therefore I added babel to compile them. Although, even after adding all required modules, and adding a mocha.opts file inside of my test directory, I still get this error
{ import sinon from 'sinon';
^^^^^
SyntaxError: Unexpected identifier
mocha.opts :
--slow 2000
--timeout 15000
--require #babel/register
--recursive test/src
package.json command:
"test": "mocha"
modules :
"#babel/cli": "^7.2.3",
"#babel/core": "^7.3.4",
"#babel/plugin-transform-runtime": "^7.3.4",
"#babel/preset-env": "^7.3.4",
"#babel/register": "^7.4.0",
"#babel/runtime": "^7.3.4",
If anything, I also added a .babelrc file in my test directory
{
"presets": ["#babel/preset-env"],
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"helpers": true,
"regenerator": true
}
]
]
}
Did I miss something ?
I had exactly the same issue, and your question gave me the answer. My .babelrc file looks like this:
{
"presets": ["#babel/preset-env"],
"comments": false,
"env": {
"test": {
"presets": [
"#babel/preset-env"
]
},
// ...Other environment settings...
},
"plugins": ["#babel/plugin-transform-runtime"]
}
Removing the helpers and regenerator parameter worked for me.

npm: How to set NODE_ENV in Windows (10)?

I am trying to add an npm script in package.json that sets NODE_ENV before doing something else (like running webpack). But although the syntax seems to be correct, NODE_ENV is not set when running under Windows 10.
Test script
"scripts": {
"test": "SET NODE_ENV=debug && echo %NODE_ENV%" }
The result from npm run test is "production" (provided NODE_ENV was set to "production" before running the script). Should be "debug".
What could be wrong? I even tried cross-env with no success.
Edit
To clarify my question: I cannot set any environment variable under Windows 10. And I need to call SET because I am running the script under Windows (10). Seems to be some rights problem (scripts not allowed to set environment variables?).
Another (or the actual) question would be: How can I create one script to build (using webpack) with creating minified versions of JavaScript files (for production), and one script to create non-minified versions (for development). So far I use following approach (see comments for the important parts):
Edit 2
I did not now that this probably made a difference, but in case it does: I worked with an React app created with create-react-app. I found the answer to my question, see below.
package.json:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
// Scipts for build for development and for production
"build-dev": "SET NODE_ENV=debug webpack",
"build-release": "SET NODE_ENV=production webpack"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-env": "^1.4.0",
"babel-preset-react": "^6.24.1",
"debug": "^2.6.4",
"webpack": "^2.4.1"
}
}
webpack.config.js:
const path = require('path');
var webpack = require('webpack');
// Check if in debug environment
var debug = process.env.NODE_ENV !== "production";
module.exports = {
context: path.join(__dirname, 'src'),
entry: ['./index.js'],
output: {
path: path.join(__dirname, 'www/js'),
filename: 'index.js',
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['babel-loader'],
}],
},
// Add the UglifyJs plugin only in debug mode
plugins: debug ? [] : [new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false })],
resolve: {
modules: [
path.join(__dirname, 'node_modules')
]
}
};
This fails because setting NODE_ENV does not work for some reason. Using the command prompt directly like in the scripts:
SET NODE_ENV = debug
webpack
works by the way. That's proof that the configuration is okay, but just the npm script cannot set NODE_ENV.
Just in case you are STILL having issues setting the NODE_ENV in Windows 10 - this will help you. In your package.json file add the following:
"test": "SET \"NODE_ENV=test\""
If you plan on pushing this to Heroku - you will have to "export" the variable and your string would look like this (you are escaping the Windows-NEEDED quotes with a slash):
"test": "export NODE_ENV=test || SET \"NODE_ENV=test\""
Lastly, if you need a following command like mocha then the line would look like this:
"test": "export NODE_ENV=test || SET \"NODE_ENV=test\" && mocha server/**/*.name_of_files_plus_test.js"
Hope this helps someone :) - Mike
I found the answer to my question in the meantime, basically in the create-react-app readme: Firstly in an app created with create-react-app NODE_ENV cannot be manually overridden. Secondly, when setting environment variables, their name must start with "REACT_APP_". This was the solution for me.
In package.json:
"scripts": {
...
"build:staging": "SET REACT_APP_ENVIRONMENT=Staging && npm run build"
}
In the code:
if (process.env.REACT_APP_ENVIRONMENT === "Staging") ...
Did you try?
set DEBUG=* & npm run test
Make sure debug already installed
npm install debug --save
UPDATE:
To set environment variable in windows use
set NODE_ENV=dev //for development environment
In your case
"scripts": {
"test": "NODE_ENV=dev && echo %NODE_ENV%" }

grunt-package-modules cannot install dependency of itself

I'm trying to use the npm package grunt-package-modules to gather my npm_module dependencies for a bundled deployment but ran into the error when running the command grunt packageModules:
Fatal error: Refusing to install test as a dependency of itself
This error typically occurs when the name of the project also appears in the list of dependencies in package.json as was the case here, but that does not occur in the original file or the one that is copied into the dist folder.
I was able to get this error with the simplest project setup I could create from the examples given in the grunt tutorial and the package wiki. Is there something I'm missing in setting up this plugin?
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"underscore": "^1.8.3"
},
"devDependencies": {
"grunt": "^1.0.1",
"grunt-package-modules": "^1.0.0"
}
}
Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
packageModules: {
dist: {
src: 'package.json',
dest: 'dist'
},
}
});
grunt.loadNpmTasks('grunt-package-modules');
}
I'm on a PC and had the same thing happen on my home PC but had my co-worker run through this same setup on his mac and it worked successfully for him. Also tried updating node and npm since we had different versions with no luck.

How to build Twitter Bootstrap 3 using Grunt

I've cloned Twitter Bootstrap 3 using git clone https://github.com/twbs/bootstrap.git:
Now, I am trying to build it using Grunt and I cannot find any documentation on how to do this.
Where should I start?
To add some more automation to your project, I would suggest you is to use Bower. This will even save you the time of downloading everything to your assets.
In order to use Bower you need bower.json
This file looks something like this:
{
"name": "WebExpressive",
"version": "0.0.0",
"authors": [
"username <username#abc.com>"
],
"description": "An awesome web application",
"license": "MIT",
"ignore": [],
"dependencies": {
"bootstrap": "latest",
"jQuery": "latest",
"angular-latest": "latest",
"turnjs": "latest"
}
}
Now you to plug your bower to grunt you need to have a Gruntfile.js which will look something like this
module.exports = function (grunt) {
//project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
shell: {
multiple: {
command: ['bower install',
'mv bower_components/** public/',
'rm -rf bower_components'].join('&&')
}
}
});
grunt.loadNpmTasks('grunt-shell');
//Default Tasks
grunt.registerTask('default', ['shell']);
//production Tasks
//grunt.registerTask('dist',[..]);
//test tasks
};
Now before you actually run the 'grunt', make sure that you got all npm packages in your project directory and package.json is in correct shape.
Take a look at my package.json file.
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"grunt": "*",
"grunt-shell": "*",
"grunt-contrib-uglify": "*",
"grunt-contrib-connect": "*",
"grunt-contrib-coffee": "*",
"grunt-contrib-compass": "*",
"grunt-open": "*",
"grunt-contrib-requirejs": "*",
"grunt-contrib-jade": "*",
"grunt-contrib-copy": "*",
"grunt-bower-install": "*"
}
}
Now you just need to run these commands and you can find the your bootstrap inside the public folder.
npm install
grunt
Please do visit grunt and grunt shell to explore more on this, they are just great.
For a basic instruction on how to build using Grunt you can refer to
http://getbootstrap.com/getting-started/
Essentially it's as easy as
grunt dist
If you are running from the command line in Windows, be sure to run cmd.exe as administrator.