Add craco webpack plugin by condition for create react app - javascript

I am using craco with create react app and I would like to add a plugin only in DEV mode or by ENV Var
my craco.config looks is:
const path = require('path');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = () => {
return {
webpack: {
alias: {
environment: path.join(
__dirname,
'src',
'environments',
process.env.CLIENT_ENV || 'production'
)
}
// plugins: [new BundleAnalyzerPlugin()]
},
jest: {
configure: {
testPathIgnorePatterns: ['<rootDir>/src/environments/'],
moduleNameMapper: {
environment: '<rootDir>/src/environments/test'
}
}
}
};
};
so I would like this BundleAnalyzerPlugin. only if the ENV param x =true or if NODE_ENV=test
while I trying to push to plugin array I got that plugin I undefined
module.exports.webpack.plugins.push(plugin)

You can set an environment variable right before any script command. For example, in your package.json, add a new line in the scripts paragraph that sets some variables:
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"analyzer": "env NODE_ENV=production ANALYZER=test yarn start"
}
In craco.config.js you can simply use:
plugins: process.env.ANALYZER === 'test' ? [new BundleAnalyzerPlugin()] : []
Now, running npm run analyzer will both, set node env to production, set a variable ANALYZER to test (used later on) and load the craco config, that will start both the webpack server and the analyser.

you can use conditions from craco like when, whenDev, whenProd, whenTest
webpack: {
plugins: [...whenDev(() => [new BundleAnalyzerPlugin()], [])]
},

Related

Customize-cra config-overrides.js is not working

I am working on the create-react-app project with typescript. I am trying to use _ (lodash) globally. I followed manuals step by step trying to figure out how to do it, but without any success.
I followed this tutorial https://www.npmjs.com/package/customize-cra. My package.json contains between dependecies:
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"react-app-rewired": "^2.1.8",
"save-dev": "^0.0.1-security"
In devDependencies:
"customize-cra": "^1.0.0"
Based on tutorials I changed also scripts:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",...
My config-overrides.js is located in root folder:
const { addDecoratorsLegacy, override, disableEsLint } = require('customize-cra')
const webpack = require('webpack')
function myOverrides(config) {
if (!config.plugins) {
config.plugins = []
}
config.plugins.push(
new webpack.ProvidePlugin({
_: 'lodash',
}),
)
return config
}
module.exports = override(
addDecoratorsLegacy(),
disableEsLint(),
myOverrides
)
I try to use join(['Hello', 'webpack'], ' ') but failed with error.
TypeScript error in C:/Users/.../webapp/src/index.tsx(27,1): Cannot find name 'join'. TS2304
Does anybody have any idea what should go wrong?
Thank you.

Lodash not TreeShaking with Webpack with Webpack 4?

I want to tree shake lodash as well as my unused multiply function from the generated bundle from webpack
I have 2 main files app.js & math.js
It contains the following code -
app.js
import map from "lodash/map";
import { sum } from "./math";
console.log("💩");
console.log(`2 + 3 = ${sum(2, 3)}`);
map([1, 2, 3], x => {
console.log(x);
});
math.js
export const sum = (a, b) => a + b;
export const multiply = (m, n) => m * n;
webpack.config.js
const path = require("path");
const webpack = require("webpack");
const UglifyJSPlugin = require("uglifyjs-webpack-plugin");
const Jarvis = require("webpack-jarvis");
let plugins = [new Jarvis()];
if (process.env.NODE_ENV === "production") plugins.push(new UglifyJSPlugin());
const config = {
entry: "./app.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: "babel-loader"
}
]
},
plugins
};
module.exports = config;
My npm script look like -
"scripts": {
"dev": "webpack --optimize-minimize --mode development",
"dev:watch": "webpack --watch --optimize-minimize --mode development",
"prod": "webpack -p --optimize-minimize --mode production",
"prod:watch": "webpack -p --watch --optimize-minimize --mode production",
"start": "npm run prod",
"clean": "rm -rf dist"
}
The complete code is available at https://github.com/deadcoder0904/webpack-treeshake
I've tried using UglifyJSPlugin but in the generated bundle it still shows my unused multiply function from math.js. Also, the production bundle generated from npm run prod remains 20kB which is a lot & I see a lot of lodash stuff included as well.
I found the answer
To use lodash with tree shaking we should first install lodash-es & then remove the lodash dependency
Also, it should not be transpiled first, so we make our .babelrc file as follows -
{
"presets": [
[
"env",
{
"modules": false
}
]
]
}
Notice, that setting modules to false makes it not transpile
And now the bundle reduces to 16.2kB & 5.79kB gzip
Some code from lodash module will still be used because it is required to run lodash itself, other than that multiply function from ./math.js isn't added in the resulting bundle
I also needed lodash-webpack-plugin for it to be working
Treeshaking works 🎉
I've made some basic repos solving the stated problem -
https://github.com/deadcoder0904/webpack-exam
https://github.com/deadcoder0904/webpack-treeshake
Building off of #deadcoder0904's answer, here's how to do the same with babel-loader in webpack 4 (instead of using .babelrc):
...
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
plugins: ['lodash'],
presets: [['env', { modules: false }]]
}
}
},
Note: I wasn't able to get this to work without explicitly importing from 'lodash-es' (even if I pointed lodash-es to lodash in my tsconfig (I'm using typescript). If someone can get this working without having to use the special import { map } from 'lodash-es'; and instead with import { map } from 'lodash'; it would be great to know how!

Webpack.config.js configuration

Hello i'm trying to install this repo https://github.com/aepsilon and i ran npm i --no-bin-links, npm i webpack -g and other package but i cannot find how to configure my webpack.config.js because i got this error everytime i run npm start
webpack-dev-server --progress --colors --display-error-details --host=0.0.0.0
how can i configure my webpack.config.js https://github.com/webpack/webpack-dev-server/issues/183
here is my webpack.config.js and package.json
'use strict';
/* eslint-env node, es6 */
const path = require('path');
const webpack = require('webpack');
/////////////
// Utility //
/////////////
/**
* Recursively merges two webpack configs.
* Concatenates arrays, and throws an error for other conflicting values.
*/
function merge(x, y) {
if (x == null) { return y; }
if (y == null) { return x; }
if (x instanceof Array && y instanceof Array) {
return x.concat(y);
} else if (Object.getPrototypeOf(x) === Object.prototype &&
Object.getPrototypeOf(y) === Object.prototype) {
// for safety, only plain objects are merged
let result = {};
(new Set(Object.keys(x).concat(Object.keys(y)))).forEach(function (key) {
result[key] = merge(x[key], y[key]);
});
return result;
} else {
throw new Error(`cannot merge conflicting values:\n\t${x}\n\t${y}`);
}
}
/////////////////
// Base Config //
/////////////////
const srcRoot = './src/';
const commonConfig = {
entry: {
TMViz: [srcRoot + 'TMViz.js'],
main: srcRoot + 'main.js'
},
output: {
library: '[name]',
libraryTarget: 'var', // allow console interaction
path: path.join(__dirname, 'build'),
publicPath: '/build/',
filename: '[name].bundle.js'
},
externals: {
'ace-builds/src-min-noconflict': 'ace',
'bluebird': 'Promise',
'clipboard': 'Clipboard',
'd3': 'd3',
'jquery': 'jQuery',
'js-yaml': 'jsyaml',
'lodash': 'lodash',
'lodash/fp': '_'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
// Note on ordering:
// Each "commons chunk" takes modules shared with any previous chunks,
// including other commons. Later commons therefore contain the fewest dependencies.
// For clarity, reverse this to be consistent with browser include order.
// names: ['util', 'TuringMachine', 'TapeViz', 'StateViz'].reverse()
names: ['TMViz'].reverse()
})
],
module: {
loaders: [
// copy files verbatim
{ test: /\.css$/,
loader: 'file',
query: {
name: '[path][name].[ext]',
context: srcRoot
}
}
]
}
};
//////////////////////
// Dev/Prod Configs //
//////////////////////
const devConfig = {
output: {pathinfo: true}
};
const prodConfig = {
devtool: 'source-map', // for the curious
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(true),
new webpack.optimize.UglifyJsPlugin({compress: {warnings: false}})
]
};
const isProduction = (process.env.NODE_ENV === 'production');
module.exports = merge(commonConfig, isProduction ? prodConfig : devConfig);
my package.json
{
"name": "turing-machine-viz",
"version": "1.0.0",
"description": "Turing machine visualization and simulator",
"homepage": "http://turingmachine.io",
"license": "BSD-3-Clause",
"author": "Andy Li <andy.srs.li#gmail.com>",
"repository": "aepsilon/turing-machine-viz",
"scripts": {
"clean": "trash build/ || rm -r build/",
"depgraph": "mkdir -p build/ && (cd src/ && madge . --dot) > build/depgraph.gv",
"depgraph-noext": "mkdir -p build/ && (cd src/ && madge . --dot -x \"`node -e \"console.log(Object.keys(require('../webpack.config').externals).map(s => '^'+s+'$').join('|'))\"`\") > build/depgraph-noext.gv",
"lint": "eslint --cache webpack.config.js src/",
"prod": "export NODE_ENV=production; npm run lint && webpack --progress --colors --display-error-details",
"start": "webpack-dev-server --progress --colors --display-error-details --host=0.0.0.0",
"watch": "webpack --watch --progress --colors --display-error-details"
},
"dependencies": {
"webpack-dev-server": "^2.9.5"
},
"devDependencies": {
"eslint": "^3.0.0",
"file-loader": "^0.8.5",
"raw-loader": "^0.5.1",
"webpack": "^1.12.9"
}
}
https://imgur.com/a/qdP18
Change the webpack version to 1.15.0 and webpack-dev-server to 1.16.5.
In the webpack.config.js line 77 change loader: 'file', to loader: 'file-loader',
Run npm install
Then enjoy your Turing Machine.
Thanks

How to remove the /******/ comments in webpack / babel

I'm trying to use babel to compile my javascript , and unless I use the --optimize-minimize flag (or -p), every single line has these /******/ comments.
How do I get rid of all comments?
I'm kicking it off with an npm script: "build:dev": "webpack -d --env=dev --config ./webpack.config.dev.js",
and my webpack.config.dev.js looks like:
const path = require('path')
module.exports = (env) => {
return {
entry: './src/js/index.js',
output: {
filename: 'js/path.js',
path: path.resolve(__dirname, 'path/static')
}
}
}

Passing environment-dependent variables in webpack

I'm trying to convert an angular app from gulp to webpack. in gulp I use gulp-preprocess to replace some variables in the html page (e.g. database name) depending on the NODE_ENV. What is the best way of achieving a similar result with webpack?
There are two basic ways to achieve this.
DefinePlugin
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
Note that this will just replace the matches "as is". That's why the string is in the format it is. You could have a more complex structure, such as an object there but you get the idea.
EnvironmentPlugin
new webpack.EnvironmentPlugin(['NODE_ENV'])
EnvironmentPlugin uses DefinePlugin internally and maps the environment values to code through it. Terser syntax.
Alias
Alternatively you could consume configuration through an aliased module. From consumer side it would look like this:
var config = require('config');
Configuration itself could look like this:
resolve: {
alias: {
config: path.join(__dirname, 'config', process.env.NODE_ENV)
}
}
Let's say process.env.NODE_ENV is development. It would map into ./config/development.js then. The module it maps to can export configuration like this:
module.exports = {
testing: 'something',
...
};
Just another option, if you want to use only a cli interface, just use the define option of webpack. I add the following script in my package.json :
"build-production": "webpack -p --define process.env.NODE_ENV='\"production\"' --progress --colors"
So I just have to run npm run build-production.
I investigated a couple of options on how to set environment-specific variables and ended up with this:
I have 2 webpack configs currently:
webpack.production.config.js
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': JSON.stringify('production'),
'API_URL': JSON.stringify('http://localhost:8080/bands')
}
}),
webpack.config.js
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': JSON.stringify('development'),
'API_URL': JSON.stringify('http://10.10.10.10:8080/bands')
}
}),
In my code I get the value of API_URL in this (brief) way:
const apiUrl = process.env.API_URL;
EDIT 3rd of Nov, 2016
Webpack docs has an example: https://webpack.js.org/plugins/define-plugin/#usage
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
VERSION: JSON.stringify("5fa3b9"),
BROWSER_SUPPORTS_HTML5: true,
TWO: "1+1",
"typeof window": JSON.stringify("object")
})
With ESLint you need to specifically allow undefined variables in code, if you have no-undef rule on. http://eslint.org/docs/rules/no-undef like this:
/*global TWO*/
console.log('Running App version ' + TWO);
EDIT 7th of Sep, 2017 (Create-React-App specific)
If you're not into configuring too much, check out Create-React-App: Create-React-App - Adding Custom Environment Variables. Under the hood CRA uses Webpack anyway.
You can pass environment variables without additional plugins using --env
Webpack 2-4
webpack --config webpack.config.js --env.foo=bar
Webpack 5+ (without.)
webpack --config webpack.config.js --env foo=bar
Then, use the variable in webpack.config.js:
module.exports = function(env) {
if (env.foo === 'bar') {
// do something
}
}
Further Reading: Webpack 2.0 doesn't support custom command line arguments?
#2254
You can directly use the EnvironmentPlugin available in webpack to have access to any environment variable during the transpilation.
You just have to declare the plugin in your webpack.config.js file:
var webpack = require('webpack');
module.exports = {
/* ... */
plugins: [
new webpack.EnvironmentPlugin(['NODE_ENV'])
]
};
Note that you must declare explicitly the name of the environment variables you want to use.
To add to the bunch of answers personally I prefer the following:
const webpack = require('webpack');
const prod = process.argv.indexOf('-p') !== -1;
module.exports = {
...
plugins: [
new webpack.DefinePlugin({
process: {
env: {
NODE_ENV: prod? `"production"`: '"development"'
}
}
}),
...
]
};
Using this there is no funky env variable or cross-platform problems (with env vars). All you do is run the normal webpack or webpack -p for dev or production respectively.
Reference: Github issue
Since my Edit on the above post by thevangelist wasn't approved, posting additional information.
If you want to pick value from package.json like a defined version number and access it through DefinePlugin inside Javascript.
{"version": "0.0.1"}
Then, Import package.json inside respective webpack.config, access the attribute using the import variable, then use the attribute in the DefinePlugin.
const PACKAGE = require('../package.json');
const _version = PACKAGE.version;//Picks the version number from package.json
For example certain configuration on webpack.config is using METADATA for DefinePlugin:
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
host: HOST,
port: PORT,
ENV: ENV,
HMR: HMR,
RELEASE_VERSION:_version//Version attribute retrieved from package.json
});
new DefinePlugin({
'ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
'process.env': {
'ENV': JSON.stringify(METADATA.ENV),
'NODE_ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
'VERSION': JSON.stringify(METADATA.RELEASE_VERSION)//Setting it for the Scripts usage.
}
}),
Access this inside any typescript file:
this.versionNumber = process.env.VERSION;
The smartest way would be like this:
// webpack.config.js
plugins: [
new webpack.DefinePlugin({
VERSION: JSON.stringify(require("./package.json").version)
})
]
Thanks to Ross Allen
Just another answer that is similar to #zer0chain's answer. However, with one distinction.
Setting webpack -p is sufficient.
It is the same as:
--define process.env.NODE_ENV="production"
And this is the same as
// webpack.config.js
const webpack = require('webpack');
module.exports = {
//...
plugins:[
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
]
};
So you may only need something like this in package.json Node file:
{
"name": "projectname",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"debug": "webpack -d",
"production": "webpack -p"
},
"author": "prosti",
"license": "ISC",
"dependencies": {
"webpack": "^2.2.1",
...
}
}
Just a few tips from the DefinePlugin:
The DefinePlugin allows you to create global constants which can be configured at compile time. This can be useful for allowing different behavior between development builds and release builds. For example, you might use a global constant to determine whether logging takes place; perhaps you perform logging in your development build but not in the release build. That's the sort of scenario the DefinePlugin facilitates.
That this is so you can check if you type webpack --help
Config options:
--config Path to the config file
[string] [default: webpack.config.js or webpackfile.js]
--env Enviroment passed to the config, when it is a function
Basic options:
--context The root directory for resolving entry point and stats
[string] [default: The current directory]
--entry The entry point [string]
--watch, -w Watch the filesystem for changes [boolean]
--debug Switch loaders to debug mode [boolean]
--devtool Enable devtool for better debugging experience (Example:
--devtool eval-cheap-module-source-map) [string]
-d shortcut for --debug --devtool eval-cheap-module-source-map
--output-pathinfo [boolean]
-p shortcut for --optimize-minimize --define
process.env.NODE_ENV="production"
[boolean]
--progress Print compilation progress in percentage [boolean]
I found the following solution to be easiest to setup environment variable for Webpack 2:
For example we have a webpack settings:
var webpack = require('webpack')
let webpackConfig = (env) => { // Passing envirmonment through
// function is important here
return {
entry: {
// entries
},
output: {
// outputs
},
plugins: [
// plugins
],
module: {
// modules
},
resolve: {
// resolves
}
}
};
module.exports = webpackConfig;
Add Environment Variable in Webpack:
plugins: [
new webpack.EnvironmentPlugin({
NODE_ENV: 'development',
}),
]
Define Plugin Variable and add it to plugins:
new webpack.DefinePlugin({
'NODE_ENV': JSON.stringify(env.NODE_ENV || 'development')
}),
Now when running webpack command, pass env.NODE_ENV as argument:
webpack --env.NODE_ENV=development
// OR
webpack --env.NODE_ENV development
Now you can access NODE_ENV variable anywhere in your code.
I prefer using .env file for different environment.
Use webpack.dev.config to copy env.dev to .env into root folder
Use webpack.prod.config to copy env.prod to .env
and in code
use
require('dotenv').config();
const API = process.env.API ## which will store the value from .env file
My workaround for the webpack version "webpack": "^4.29.6" is very simple.
//package.json
{
...
"scripts": {
"build": "webpack --mode production",
"start": "webpack-dev-server --open --mode development"
},
}
you can pass --mode parameter with your webpack commnad then in webpack.config.js
// webpack.config.json
module.exports = (env,argv) => {
return {
...
externals: {
// global app config object
config: JSON.stringify({
apiUrl: (argv.mode==="production") ? '/api' : 'localhost:3002/api'
})
}
}
And I use baseurl in my code like this
// my api service
import config from 'config';
console.log(config.apiUrl) // like fetch(`${config.apiUrl}/users/user-login`)
To add to the bunch of answers:
Use ExtendedDefinePlugin instead of DefinePlugin
npm install extended-define-webpack-plugin --save-dev.
ExtendedDefinePlugin is much simpler to use and is documented :-)
link
Because DefinePlugin lacks good documentation, I want to help out, by saying that it actually works like #DEFINE in c#.
#if (DEBUG)
Console.WriteLine("Debugging is enabled.");
#endif
Thus, if you want to understand how DefinePlugin works, read the c# #define doucmentation. link
Since Webpack v4, simply setting mode in your Webpack config will set the NODE_ENV for you (via DefinePlugin). Docs here.
Here is a way that has worked for me and has allowed me keep my environment variables DRY by reusing a json file.
const webpack = require('webpack');
let config = require('./settings.json');
if (__PROD__) {
config = require('./settings-prod.json');
}
const envVars = {};
Object.keys(config).forEach((key) => {
envVars[key] = JSON.stringify(config[key]);
});
new webpack.DefinePlugin({
'process.env': envVars
}),
dotenv-webpack
A secure webpack plugin that supports dotenv and other environment variables and only exposes what you choose and use.
with some workaround with configuration based on defaults option to achieve that, once the package has .env.defaults file to as initial values for env variables you can use it for development and let .env for your production.
Usage
install the package
npm install dotenv-webpack --save-dev
Create a .env.defaults file
API_URL='dev_url/api/'
create a .env file leave it empty, let defaults works, update it on your deploy process
config webpack - webpack.config.js
new Dotenv({
defaults: true
})
dev environement test file.js
console.log(process.env.API_URL)
// Outputs: dev_url/api/
on build, update empty .env file
API_URL='prod_url/api/'
dotenv-webpack will use this to and override env.defaults
prod environement test file.js
console.log(process.env.API_URL)
// Outputs: prod_url/api/
dotenv-webpack
dotenv-defaults
I'm not a huge fan of...
new webpack.DefinePlugin({
'process.env': envVars
}),
...as it does not provides any type of security. instead, you end up boosting your secret stuff, unless you add a webpack to gitignore 🤷‍♀️ there is a better solution.
Basically with this config once you compile your code all the process env variables will be removed from the entire code, there is not going to be a single process.env.VAR up thanks to the babel plugin transform-inline-environment-variables
PS if you do not want to end up with a whole bunch of undefines, make sure you call the env.js before webpack calls babel-loader, that's why it is the first thing webpack calls. the array of vars in babel.config.js file must match the object on env.js. now there is only one mow thing to do.
add a .env file put all your env variables there, the file must be at the root of the project or feel free to add it where ever u want, just make sure to set the same location on the env.js file and also add it to gitignore
const dotFiles = ['.env'].filter(Boolean);
if (existsSync(dotFiles)) {
require("dotenv-expand")(require("dotenv").config((dotFiles)));
}
If you want to see the whole babel + webpack + ts get it from heaw
https://github.com/EnetoJara/Node-typescript-babel-webpack.git
and same logic applies to react and all the other 💩
config
---webpack.js
---env.js
src
---source code world
.env
bunch of dotFiles
env.js
"use strict";
/***
I took the main idea from CRA, but mine is more cooler xD
*/
const {realpathSync, existsSync} = require('fs');
const {resolve, isAbsolute, delimiter} = require('path');
const NODE_ENV = process.env.NODE_ENV || "development";
const appDirectory = realpathSync(process.cwd());
if (typeof NODE_ENV !== "string") {
throw new Error("falle and stuff");
}
const dotFiles = ['.env'].filter(Boolean);
if (existsSync(dotFiles)) {
require("dotenv-expand")(require("dotenv").config((dotFiles)));
}
process.env.NODE_PATH = (process.env.NODE_PATH || "")
.split(delimiter)
.filter(folder => folder && isAbsolute(folder))
.map(folder => resolve(appDirectory, folder))
.join(delimiter);
const ENETO_APP = /^ENETO_APP_/i;
module.exports = (function () {
const raw = Object.keys ( process.env )
.filter ( key => ENETO_APP.test ( key ) )
.reduce ( ( env, key ) => {
env[ key ] = process.env[ key ];
return env;
},
{
BABEL_ENV: process.env.ENETO_APP_BABEL_ENV,
ENETO_APP_DB_NAME: process.env.ENETO_APP_DB_NAME,
ENETO_APP_DB_PASSWORD: process.env.ENETO_APP_DB_PASSWORD,
ENETO_APP_DB_USER: process.env.ENETO_APP_DB_USER,
GENERATE_SOURCEMAP: process.env.ENETO_APP_GENERATE_SOURCEMAP,
NODE_ENV: process.env.ENETO_APP_NODE_ENV,
PORT: process.env.ENETO_APP_PORT,
PUBLIC_URL: "/"
} );
const stringyField = {
"process.env": Object.keys(raw).reduce((env, key)=> {
env[key]=JSON.stringify(raw[key]);
return env;
},{}),
};
return {
raw, stringyField
}
})();
webpack file with no plugins troll
"use strict";
require("core-js");
require("./env.js");
const path = require("path");
const nodeExternals = require("webpack-node-externals");
module.exports = env => {
return {
devtool: "source-map",
entry: path.join(__dirname, '../src/dev.ts'),
externals: [nodeExternals()],
module: {
rules: [
{
exclude: /node_modules/,
test: /\.ts$/,
use: [
{
loader: "babel-loader",
},
{
loader: "ts-loader"
}
],
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: "file-loader",
},
],
},
],
},
node: {
__dirname: false,
__filename: false,
},
optimization: {
splitChunks: {
automaticNameDelimiter: "_",
cacheGroups: {
vendor: {
chunks: "initial",
minChunks: 2,
name: "vendor",
test: /[\\/]node_modules[\\/]/,
},
},
},
},
output: {
chunkFilename: "main.chunk.js",
filename: "name-bundle.js",
libraryTarget: "commonjs2",
},
plugins: [],
resolve: {
extensions: ['.ts', '.js']
} ,
target: "node"
};
};
babel.config.js
module.exports = api => {
api.cache(() => process.env.NODE_ENV);
return {
plugins: [
["#babel/plugin-proposal-decorators", { legacy: true }],
["#babel/plugin-transform-classes", {loose: true}],
["#babel/plugin-external-helpers"],
["#babel/plugin-transform-runtime"],
["#babel/plugin-transform-modules-commonjs"],
["transform-member-expression-literals"],
["transform-property-literals"],
["#babel/plugin-transform-reserved-words"],
["#babel/plugin-transform-property-mutators"],
["#babel/plugin-transform-arrow-functions"],
["#babel/plugin-transform-block-scoped-functions"],
[
"#babel/plugin-transform-async-to-generator",
{
method: "coroutine",
module: "bluebird",
},
],
["#babel/plugin-proposal-async-generator-functions"],
["#babel/plugin-transform-block-scoping"],
["#babel/plugin-transform-computed-properties"],
["#babel/plugin-transform-destructuring"],
["#babel/plugin-transform-duplicate-keys"],
["#babel/plugin-transform-for-of"],
["#babel/plugin-transform-function-name"],
["#babel/plugin-transform-literals"],
["#babel/plugin-transform-object-super"],
["#babel/plugin-transform-shorthand-properties"],
["#babel/plugin-transform-spread"],
["#babel/plugin-transform-template-literals"],
["#babel/plugin-transform-exponentiation-operator"],
["#babel/plugin-proposal-object-rest-spread"],
["#babel/plugin-proposal-do-expressions"],
["#babel/plugin-proposal-export-default-from"],
["#babel/plugin-proposal-export-namespace-from"],
["#babel/plugin-proposal-logical-assignment-operators"],
["#babel/plugin-proposal-throw-expressions"],
[
"transform-inline-environment-variables",
{
include: [
"ENETO_APP_PORT",
"ENETO_APP_NODE_ENV",
"ENETO_APP_BABEL_ENV",
"ENETO_APP_DB_NAME",
"ENETO_APP_DB_USER",
"ENETO_APP_DB_PASSWORD",
],
},
],
],
presets: [["#babel/preset-env",{
targets: {
node: "current",
esmodules: true
},
useBuiltIns: 'entry',
corejs: 2,
modules: "cjs"
}],"#babel/preset-typescript"],
};
};
now 2020, i am face to same question, but for this old question, there are so many new answer, just list some of it:
this is webpack.config.js
plugins: [
new HtmlWebpackPlugin({
// 1. title is the parameter, you can use in ejs template
templateParameters:{
title: JSON.stringify(someting: 'something'),
},
}),
//2. BUILT_AT is a parameter too. can use it.
new webpack.DefinePlugin({
BUILT_AT: webpack.DefinePlugin.runtimeValue(Date.now,"some"),
}),
//3. for webpack5, you can use global variable: __webpack_hash__
//new webpack.ExtendedAPIPlugin()
],
//4. this is not variable, this is module, so use 'import tt' to use it.
externals: {
'ex_title': JSON.stringify({
tt: 'eitentitle',
})
},
the 4 ways only basic, there are even more ways that i believe. but i think maybe this 4ways is the most simple.

Categories