How to pass output path to webpack as parameter using npm? - angularjs

I have a Angular application that uses Webpack as module bundler. In my package.json, I have the following scripts:
"scripts": {
"start": "webpack",
"start-in-war": "??????"
}
Also, this is the output portion of my webpack.config.js
output: {
path: __dirname + "/dist/",
filename: "app.js"
}
Since I also want this application to be packaged into a WAR file with my backend service, I need to pass that path field as parameter, so I will mantain both configurations: the default that is more development-friendly (I don't have to deploy the application anytime I make a client change) and the one I will ultimately use (that would be the "start-in-war" parameter).
How can I achieve that?
Note: The start-in-war script is not gonna be used just for production, also development.

Related

How to create multiple entry points(index.js) for a single react application?

I want to create two different builds for a single application. When I do an npm run build, it runs webpack and generates a build, and injects that build into the index.html file. What I ideally want to do is tell webpack to create one build from index.js and another build from index2.js. How do I achieve this? Looked into module federation, but wasn't able to figure out how to do this in a single application.
You can do this settings in webpack.config.js.
module.exports = {
entry: {
bundle1: "path for index1.js",
bundle2: "path for index2.js"
},
output: {
// `filename` provides a template for naming your bundles (remember to use `[name]`)
filename: '[name].js'
publicPath: 'Path for saving directory'
}};

Environment variables Laravel Mix in Docker

We have a Laravel 8 application with Laravel Mix 6.0.49 and a React frontend. The application runs inside a docker container in production and development. Up until now, the frontend was compiled outside the docker container for some reason, but since we are moving to a fully dockerized environment, we are required to call the frontend scripts from inside the container. This all works fine, except for an environment variable we are setting in package.json, which allows us to pass the version of the app as a mix variable. Here is the current setup:
// package.json
"version": "0.1.1",
"scripts": {
...
"watch": "cross-env APP_VERSION=$(node -pe 'require(\"./package.json\").version') mix watch",
...
// .env
...
MIX_APP_VERSION="${APP_VERSION}"
...
// MyComponent.jsx
...
<div>version {process.env.MIX_APP_VERSION}</div>
...
The environment variable worked fine when the watch script was called outside the docker container.
Has anyone any idea of why it suddenly does not work anymore? I'm open to other ways of approaching this too.
I fixed this issue in the end by removing the variable related stuff from package.json including the cross-env dependency and setting the environment variable through the webpack config instead (webpack.mix.js)
...
.webpackConfig({
plugins: [
new webpack.DefinePlugin({
'process.env.APP_VERSION': JSON.stringify(
process.env.npm_package_version,
),
}),
],
})

Environment variables in manifest.json - Chrome Extension

Is it possible to set environment variables in the manifest.json file of a Chrome Extension?
Like wOxxOm said, I used webpack to proccess manifest.json.
In my case, I needed to set version automatically on manifest file.
I added to webpack script:
plugins: [
new CopyWebpackPlugin([
{
from: "public/manifest.json",
to: "manifest.json",
transform(content, path) {
return modify(content)
}
}
]),
]
And the modify function replaces version on file for the parameter:
function modify(buffer) {
var manifest = JSON.parse(buffer.toString());
let argv = process.argv[2];
if (argv) manifest.version = argv.split("=")[1];
let manifest_JSON = JSON.stringify(manifest, null, 2);
return manifest_JSON;
}
So, I build like "yarn build --version=x.x" and webpack do what I need.
PS: if you're going to use this, remember to change:
the manifest.json directory, if necessary;
the value in the modify function, in my case it was version
As the OP has mentioned in her answer, using the copy-webpack-plugin in the webpack.config.js file is the way to go if you're building your Chrome Extension with React. However, if your React app is based on create-react-app, directly editing the webpack.config.js file (which is located in node_modules/react-scripts/config) is not recommended.
In such a case, use craco, which is an npm package that can be used to customize an app based on create-react-app. Here's how you do it:
Install craco into your project using npm i #craco/craco.
Install copy-webpack-plugin as a dev-dependency in your project using npm i --save-dev copy-webpack-plugin.
Let's suppose we're creating a development and a production build of our Chrome Extension. Let's also suppose we've already assigned "version": "0.1.0" in our Chrome Extension's manifest.json. Depending on the build type, we'd like to assign accordingly the version_name field in our Chrome Extension's manifest.json, e.g., "version_name": "0.1.0 dev" for development and "version_name": "0.1.0" for production. In your React app's package.json, introduce two fields (the script names can be whatever you wish) as follows:
"scripts": {
...
"build-dev": "CRX_ENV=dev craco build", // or "set CRX_ENV=dev&& craco build" in the case of Windows
"build-prod": "CRX_ENV=prod craco build", // or "set CRX_ENV=prod&& craco build" in the case of Windows
...
}
Create a new file called craco.config.js in the root of your project. As per your need, do something similar to the following in the craco.config.js file:
const CopyPlugin = require("copy-webpack-plugin")
module.exports = {
webpack: {
plugins: [
new CopyPlugin({
patterns: [
{
from: "public/manifest.json",
to: "manifest.json",
transform(content, path) {
return modifyManifest(content)
},
},
],
}),
],
},
}
function modifyManifest(buffer) {
const manifest = JSON.parse(buffer.toString())
if (process.env.CRX_ENV === "dev") {
manifest.version_name = `${manifest.version} dev`
} else if (process.env.CRX_ENV === "prod") {
manifest.version_name = `${manifest.version}`
}
const manifestJson = JSON.stringify(manifest, null, 2)
return manifestJson
}
Run npm run build-dev. It will create a folder called build in your project root. This build folder is your unpacked Chrome Extension, which you can load into Chrome using the "Load unpacked" button on the chrome://extensions page. Once loaded, you should be able to see 0.1.0 dev as the version name of your Chrome Extension.
Delete the build folder created from the previous step and run npm run build-prod, and repeat the same steps. You should be able to see 0.1.0 as the version name of your Chrome Extension on the chrome://extensions page.

Webpack: difference about entry between production and development environment

I'm reading tutorial about Webpack on this: Github Webpack tutorial In this, there is a section about config webpack for production and development.
Here is development configuration:
// webpack.config.dev.js
module.exports = {
devtool: 'cheap-eval-source-map',
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/dev-server',
'./src/index'
],
Here is production configuration:
// webpack.config.prod.js
module.exports = {
devtool: 'source-map',
entry: ['./src/index'],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
I understand the difference in option of devtool. The thing I don't understand about entry. Why in production, entry is only about src/index but in development configuration, entry also includes webpack-dev-server
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/dev-server',
'./src/index'
The lines 'webpack-dev-server/client?http://localhost:8080' and 'webpack/hot/dev-server' are configuring/defining which port to attach an active websocket to, in this case localhost:8080, and the content base which in this case is folder/path /client. In a production environment you would never run webpack-dev-server as your bundled client assets (bundle.js or similar) would be served by a server (IIS, Node, etc), that is why there are no webpack related items in entry of the production configuration.
The Webpack plugin in question webpack-dev-server is not required to run Webpack and compile your JS sources, it simply is a tool that can be used during the development process to watch for changes and reload changes.
Technically the entry array property in development could simply be the './src/index', but then it wouldn't enable the webpack-dev-server and/or it's hot module reloading. If you wanted to run webpack-dev-server without these configuration items then you'd then need to add command line arguments when starting webpack to specify the port and/or content base.
Hopefully that helps!
Here is the 2 things you should know before understanding:
As your linked in Webpack the confusing part, there are 3 types of entry: String Array and Object. As above code, that is array type. Meaning of entry array is: Webpack will merged all those javascript files in array together. This is often unnecessary because Webpack is intelligent enough to know which javascript files need to merge while processing. You often need to do this to enhance some features from different javascript files that you don't include somewhere else in your code.
This is "little tricky" part. You see webpack/hot/dev-serverand webpack-dev-server/client?http://localhost:8080 look like a web url rather than some javascript files, right? If you check your project directory, you see there are those files: your_app_directory/node_modules/webpack/hot/dev-server.js and your_app_directory/node_modules/webpack-dev-server/client.js. And that is the real meaning: you are importing two javascript files from two modules webpack-dev-server and webpack.
Back again to your webpack configuration:
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/dev-server',
'./src/index'
],
That means we will merge three different javascript files together as point 2 I have figured out. As I explain in point 1, you will do this for enhancing some features. You include file webpack-dev-server/client.js for making a server for serving your code. You include file webpack/hot/dev-server.js for allowing your code autoloading. This is super useful when you in development mode without start/stop server each time you modify your code.

How to turn on/off ReactJS 'development mode'?

Started using ReactJS's prop validation feature, which as the docs say only works in 'development mode' for performance reasons.
React seems to be validating the properties of a particular component I've annotated, but I don't remember explicitly turning on 'development mode'.
I tried searching for how to trigger/toggle development mode, but haven't had any luck.
The other answer assumes you are using external pre-built files from react, and while correct that is not how most folks are going to or should consume React as a package. Moreover, at this point most every React library and package also relies on the same convention to toggle dev time helpers off during production. Just using the minified react will leave all those potential optimizations on the table as well.
Ultimately the magic comes down to React embedding references to process.env.NODE_ENV throughout the codebase; these act like a feature toggle.
if (process.env.NODE_ENV !== "production")
// do propType checks
The above is the most common pattern, and other libraries follow it as well. So to "disable" these checks we need to toggle NODE_ENV to "production"
The proper way to disable "dev mode" is through your bundler of choice.
webpack
Use the DefinePlugin in your webpack config like so:
new webpack.DefinePlugin({
"process.env.NODE_ENV": JSON.stringify("production")
})
Browserify
Use the Envify transform and run your browserify build step with NODE_ENV=production ("set NODE_ENV=production" on Windows)
Result
This will produce output bundles that has all instances of process.env.NODE_ENV replaced with the string literal: "production"
Bonus
When minifying the transformed code you can take advantage of "Dead Code Elimination". DCE is when the minifier is smart enough to realize that: "production" !== "production" is always false and so will just remove any code in the if block saving you bytes.
Yeah, it's not really well documented, but on the ReactJS download page it talks about development and production modes:
We provide two versions of React: an uncompressed version for development and a minified version for production. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages.
Basically, the unminified version of React is "development" mode, and the minified version of React is "production" mode.
To be in "production" mode, just include the minified version react-0.9.0.min.js
I posted this elsewhere but, frankly, here would be a better place.
Assuming you install React 15.0.1 with npm, import react from 'react' or react = require('react') will run ./mode_modules/react/lib/React.js which is React's raw source.
The React docs suggest you use ./mode_modules/react/dist/react.js for development and react.min.js for production.
Should you minify /lib/React.js or /dist/react.js for production, React will display a warning message that you've minified non-production code:
Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster. See fb.me/react-minification for more details.
react-dom, redux, react-redux behave similarly. Redux displays a warning message. I believe react-dom does too.
So you are clearly encouraged to use the production version from /dist.
However if you minify the /dist versions, webpack's UglifyJsPlugin will complain.
WARNING in ../~/react/dist/react.js
Critical dependencies:
4:478-485 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.
# ../~/react/dist/react.js 4:478-4851
You cannot avoid this message because UglifyJsPlugin can only exclude webpack chunks, not individual files.
I use the both the development and production /dist versions myself.
Webpack has less work to do and finishes a bit sooner. (YRMV)
React docs say /dist/react.min.js is optimised for production. I've read no proof that 'process.env': { NODE_ENV: JSON.stringify(IS_PRODUCTION ? 'production' : 'development') } plus uglify does as good a job as '/dist/react.min.js`. I've read no proof you get the same resulting code.
I get 1 warning message from uglify rather than 3 from the react/redux ecosystem.
You can have webpack use the /dist versions with:
resolve: {
alias: {
'react$': path.join(__dirname, 'node_modules', 'react','dist',
(IS_PRODUCTION ? 'react.min.js' : 'react.js')),
'react-dom$': path.join(__dirname, 'node_modules', 'react-dom','dist',
(IS_PRODUCTION ? 'react-dom.min.js' : 'react-dom.js')),
'redux$': path.join(__dirname, 'node_modules', 'redux','dist',
(IS_PRODUCTION ? 'redux.min.js' : 'redux.js')),
'react-redux$': path.join(__dirname, 'node_modules', 'react-redux','dist',
(IS_PRODUCTION ? 'react-redux.min.js' : 'react-redux.js'))
}
}
For webpack based build, I used to setup separate webpack.config.js for DEV and PROD. For Prod, resolve the alias as below
alias: {
'react$': path.join(__dirname, 'node_modules', 'react','dist','react.min.js'),
'react-dom$': path.join(__dirname, 'node_modules', 'react-dom','dist','react-dom.min.js')
}
You can find the working one from here
If you're working from something like this ReactJS.NET / Webpack tutorial, you can't use process.env to switch React development mode on/off as far as I can tell. This sample links to react.js directly (see Index.cshtml), so you just have to pick .min.js or the non-minified variant by changing the URL.
I'm not sure why that is the case, because the sample's webpack.config.js has a comment that seems to imply the externals: { react: 'React' } would do the job, but then goes ahead and includes react directly into the page.
I use a manual build process that runs through Webpack, so it was a two-step process for me:
Set the environment variable from package.json using the cross-env package:
"scripts": {
"build-dev": "cross-env NODE_ENV=development webpack --config webpack.config.js",
"build-prod": "cross-env NODE_ENV=production webpack --config webpack.config.js"
}
Change the webpack.config.js file to use the environment variable (which is passed-on to React to determine if we are in development or production mode), and disable minimizing the produced bundle if we are in development mode so we can see the actual names of our components. We need to use webpack's optimization property in our webpack.config.js file for this:
optimization: {
nodeEnv: process.env.NODE_ENV,
minimize: process.env.NODE_ENV === 'production'
}
webpack v4.41.5, React v16.9.19, cross-env v7.0.0, node v10.16.14
For only Webpack v4 users:
Specifying mode: production and mode: development in your Webpack config will define process.env.NODE_ENV using the DefinePlugin by default. No additional code necessary!
webpack.prod.js (taken from docs)
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'production',
});
And in our JS:
console.log(process.env.NODE_ENV) // --> 'development' or 'production'
Webpack Docs: https://webpack.js.org/guides/production/#specify-the-mode

Resources