Skip to content

Instantly share code, notes, and snippets.

@emirotin
Created April 14, 2017 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emirotin/1b2512114826e564291667aeb17895c9 to your computer and use it in GitHub Desktop.
Save emirotin/1b2512114826e564291667aeb17895c9 to your computer and use it in GitHub Desktop.
create-react-app config for Webpack2
var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var ManifestPlugin = require('webpack-manifest-plugin');
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
var getClientEnvironment = require('./env');
var paths = require('./paths');
module.exports = (isDev) => {
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
// In development, we always serve from the root. This makes config easier.
var publicPath = isDev ? '/' : paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
var shouldUseRelativeAssetPaths = !isDev && publicPath === './';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
var publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
var env = getClientEnvironment(publicUrl);
// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (!isDev && env.stringified['process.env'].NODE_ENV !== '"production"') {
throw new Error('Production builds must have NODE_ENV=production.');
}
// Note: defined here because it will be used more than once.
const cssFilename = isDev ? undefined : 'static/css/[name].[contenthash:8].css';
const minifyConfig = isDev ? undefined : {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
}
const cssLoaderConfig = { loader: 'css-loader', options: { 'importLoaders': 1 } }
const postcssLoaderConfig = {
loader: 'postcss-loader',
options: {
plugins: function () {
return [
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
]
}),
];
}
}
}
// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
// Making sure that the publicPath goes back to to build folder.
? { publicPath: Array(cssFilename.split('/').length).join('../') }
: undefined;
return {
// Don't attempt to continue if there are any errors.
bail: !isDev,
// In development you may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
// We generate sourcemaps in production. This is slow but gives good results.
// You can exclude the *.map files from the build during deployment.
devtool: isDev ? 'cheap-module-source-map' : 'source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
// The first entry point enable "hot" CSS and auto-refreshes for JS.
// In production, we only want to load the polyfills and the app code.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
isDev && require.resolve('react-dev-utils/webpackHotDevClient'),
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// Finally, this is your app's code:
isDev ? paths.appIndexJs : paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
].filter(x => !!x),
output: {
// The build folder.
path: paths.appBuild,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: isDev,
// In development this does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
// In production it's the generated JS file names (with nested folders).
// There will be one main bundle, and one file per asynchronous chunk.
// We don't currently advertise code splitting but Webpack supports it.
filename: isDev ? 'static/js/bundle.js' : 'static/js/[name].[chunkhash:8].js',
chunkFilename: !isDev ? 'static/js/[name].[chunkhash:8].chunk.js' : undefined,
// This is the URL that app is served from. We use "/" in development.
// In production we inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We read `NODE_PATH` environment variable in `paths.js` and pass paths here.
// We use `fallback` instead of `root` because we want `node_modules` to "win"
// if there any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: [ 'node_modules' ].concat(paths.nodePaths),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
extensions: ['.js', '.json', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web'
}
},
module: {
rules: [
// ** ADDING/UPDATING LOADERS **
// The "url" loader handles all assets unless explicitly excluded.
// The `exclude` list *must* be updated with every change to loader extensions.
// When adding a new loader, you must add its `test`
// as a new entry in the `exclude` list for "url" loader.
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx)$/,
loader: 'eslint-loader',
include: paths.appSrc,
enforce: "pre",
},
// "url" loader embeds assets smaller than specified size as data URLs to avoid requests.
// Otherwise, it acts like the "file" loader.
{
exclude: [
/\.html$/,
// We have to write /\.(js|jsx)(\?.*)?$/ rather than just /\.(js|jsx)$/
// because you might change the hot reloading server from the custom one
// to Webpack's built-in webpack-dev-server/client?/, which would not
// get properly excluded by /\.(js|jsx)$/ because of the query string.
// Webpack 2 fixes this, but for now we include this hack.
// https://github.com/facebookincubator/create-react-app/issues/1713
isDev ? /\.(js|jsx)(\?.*)?$/ : /\.(js|jsx)$/,
/\.css$/,
/\.json$/,
/\.svg$/
],
loader: 'url-loader',
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]'
}
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: 'babel-loader',
options: isDev ? {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true
} : undefined
},
// The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
// If you use code splitting, however, any async bundles will still
// use the "style" loader inside the async code so CSS from them won't be
// in the main CSS file.
{
test: /\.css$/,
use: isDev
? [ 'style-loader', cssLoaderConfig, postcssLoaderConfig ]
: ExtractTextPlugin.extract(Object.assign({
fallback: 'style-loader',
use: [ cssLoaderConfig, postcssLoaderConfig ]
}, extractTextPluginOptions))
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
},
// "file" loader for svg
{
test: /\.svg$/,
loader: 'file-loader',
options: {
name: 'static/media/[name].[hash:8].[ext]'
}
}
// ** STOP ** Are you adding a new loader?
// Remember to add the new extension(s) to the "url" loader exclusion list.
]
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
// In production, it will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
minify: minifyConfig,
}),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
isDev && new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
isDev && new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
isDev && new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Compat!
new webpack.LoaderOptionsPlugin({
minimize: !isDev,
debug: isDev,
options: {
context: __dirname
}
}),
// Minify the code.
!isDev && new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
screw_ie8: true, // React doesn't support IE8
warnings: false
},
mangle: {
screw_ie8: true
},
output: {
comments: false,
screw_ie8: true
}
}),
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
!isDev && new ExtractTextPlugin(cssFilename),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
!isDev && new ManifestPlugin({
fileName: 'asset-manifest.json'
})
].filter(x => !!x),
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};
}
{
"name": "spin-brush-proto",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^15.5.4",
"react-dom": "^15.5.4"
},
"devDependencies": {
"autoprefixer": "^6.7.2",
"babel-core": "^6.22.1",
"babel-eslint": "^7.1.1",
"babel-jest": "^18.0.0",
"babel-loader": "^6.2.10",
"babel-preset-react-app": "^2.2.0",
"babel-runtime": "^6.20.0",
"case-sensitive-paths-webpack-plugin": "^2.0.0",
"chalk": "^1.1.3",
"connect-history-api-fallback": "^1.3.0",
"cross-spawn": "^5.0.0",
"css-loader": "^0.28.0",
"detect-port": "^1.1.0",
"dotenv": "^4.0.0",
"eslint": "^3.16.1",
"eslint-config-react-app": "^0.6.2",
"eslint-loader": "^1.6.0",
"eslint-plugin-flowtype": "^2.21.0",
"eslint-plugin-import": "^2.0.1",
"eslint-plugin-jsx-a11y": "^4.0.0",
"eslint-plugin-react": "^6.4.1",
"extract-text-webpack-plugin": "^2.0.0",
"file-loader": "^0.11.0",
"fs-extra": "^2.1.0",
"html-webpack-plugin": "^2.24.0",
"http-proxy-middleware": "^0.17.3",
"jest": "^18.1.0",
"json-loader": "^0.5.4",
"object-assign": "^4.1.1",
"postcss-loader": "^1.2.2",
"promise": "^7.1.1",
"react-dev-utils": "^0.5.2",
"style-loader": "^0.16.1",
"url-loader": "^0.5.7",
"webpack": "^2.4.0",
"webpack-dev-server": "^2.4.2",
"webpack-manifest-plugin": "^1.1.0",
"whatwg-fetch": "^2.0.2"
},
"scripts": {
"start": "node scripts/start.js",
"build": "node scripts/build.js",
"test": "node scripts/test.js --env=jsdom"
},
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testPathIgnorePatterns": [
"<rootDir>[/\\\\](build|docs|node_modules|scripts)[/\\\\]"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
}
},
"babel": {
"presets": [
"react-app"
]
},
"eslintConfig": {
"extends": "react-app"
}
}
var buildWebpackConfig = require('./build-webpack-config');
module.exports = buildWebpackConfig(true);
var buildWebpackConfig = require('./build-webpack-config');
module.exports = buildWebpackConfig(false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment