UNPKG

15.4 kBJavaScriptView Raw
1'use strict';
2
3const autoprefixer = require('autoprefixer');
4const path = require('path');
5const webpack = require('webpack');
6const HtmlWebpackPlugin = require('html-webpack-plugin');
7const ExtractTextPlugin = require('extract-text-webpack-plugin');
8const ManifestPlugin = require('webpack-manifest-plugin');
9const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
10const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
11const eslintFormatter = require('react-dev-utils/eslintFormatter');
12const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
13const paths = require('./paths');
14const getClientEnvironment = require('./env');
15
16// Webpack uses `publicPath` to determine where the app is being served from.
17// It requires a trailing slash, or the file assets will get an incorrect path.
18const publicPath = paths.servedPath;
19// Some apps do not use client-side routing with pushState.
20// For these, "homepage" can be set to "." to enable relative asset paths.
21const shouldUseRelativeAssetPaths = publicPath === './';
22// Source maps are resource heavy and can cause out of memory issue for large source files.
23const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
24// `publicUrl` is just like `publicPath`, but we will provide it to our app
25// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
26// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
27const publicUrl = publicPath.slice(0, -1);
28// Get environment variables to inject into our app.
29const env = getClientEnvironment(publicUrl);
30
31// Assert this just to be safe.
32// Development builds of React are slow and not intended for production.
33if (env.stringified['process.env'].NODE_ENV !== '"production"') {
34 throw new Error('Production builds must have NODE_ENV=production.');
35}
36
37// Note: defined here because it will be used more than once.
38const cssFilename = 'index.css';
39
40// ExtractTextPlugin expects the build output to be flat.
41// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
42// However, our output is structured with css, js and media folders.
43// To have this structure working with relative paths, we have to use custom options.
44const extractTextPluginOptions = shouldUseRelativeAssetPaths
45 ? // Making sure that the publicPath goes back to to build folder.
46 { publicPath: Array(cssFilename.split('/').length).join('../') }
47 : {};
48
49// This is the production configuration.
50// It compiles slowly and is focused on producing a fast and minimal bundle.
51// The development configuration is different and lives in a separate file.
52module.exports = {
53 // Don't attempt to continue if there are any errors.
54 bail: true,
55 // We generate sourcemaps in production. This is slow but gives good results.
56 // You can exclude the *.map files from the build during deployment.
57 devtool: shouldUseSourceMap ? 'source-map' : false,
58 // In production, we only want to load the polyfills and the app code.
59 entry: [paths.appLibJs],
60 output: {
61 // The build folder.
62 path: paths.appBuild,
63 // Generated JS file names (with nested folders).
64 // There will be one main bundle, and one file per asynchronous chunk.
65 // We don't currently advertise code splitting but Webpack supports it.
66 filename: 'index.js',
67 //chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
68 // We inferred the "public path" (such as / or /my-project) from homepage.
69 // publicPath: publicPath,
70 library: 'kara-uc',
71 libraryTarget: 'commonjs2',
72 // Point sourcemap entries to original disk location (format as URL on Windows)
73 devtoolModuleFilenameTemplate: info =>
74 path
75 .relative(paths.appSrc, info.absoluteResourcePath)
76 .replace(/\\/g, '/'),
77 },
78 externals: {
79 react: {
80 root: 'React',
81 commonjs2: 'react',
82 commonjs: 'react',
83 amd: 'react',
84 },
85 'react-dom': {
86 root: 'ReactDOM',
87 commonjs2: 'react-dom',
88 commonjs: 'react-dom',
89 amd: 'react-dom',
90 },
91 karaui: 'karaui'
92 },
93 resolve: {
94 // This allows you to set a fallback for where Webpack should look for modules.
95 // We placed these paths second because we want `node_modules` to "win"
96 // if there are any conflicts. This matches Node resolution mechanism.
97 // https://github.com/facebookincubator/create-react-app/issues/253
98 modules: ['node_modules', paths.appNodeModules].concat(
99 // It is guaranteed to exist because we tweak it in `env.js`
100 process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
101 ),
102 // These are the reasonable defaults supported by the Node ecosystem.
103 // We also include JSX as a common component filename extension to support
104 // some tools, although we do not recommend using it, see:
105 // https://github.com/facebookincubator/create-react-app/issues/290
106 // `web` extension prefixes have been added for better support
107 // for React Native Web.
108 extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
109 alias: {
110
111 // Support React Native Web
112 // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
113 'react-native': 'react-native-web',
114 },
115 plugins: [
116 // Prevents users from importing files from outside of src/ (or node_modules/).
117 // This often causes confusion because we only process files within src/ with babel.
118 // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
119 // please link the files into your node_modules/ and let module-resolution kick in.
120 // Make sure your source files are compiled, as they will not be processed in any way.
121 new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
122 ],
123 },
124 module: {
125 strictExportPresence: true,
126 rules: [
127 // TODO: Disable require.ensure as it's not a standard language feature.
128 // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
129 // { parser: { requireEnsure: false } },
130
131 // First, run the linter.
132 // It's important to do this before Babel processes the JS.
133 {
134 test: /\.(js|jsx|mjs)$/,
135 enforce: 'pre',
136 use: [
137 {
138 options: {
139 formatter: eslintFormatter,
140 eslintPath: require.resolve('eslint'),
141
142 },
143 loader: require.resolve('eslint-loader'),
144 },
145 ],
146 include: paths.appSrc,
147 },
148 {
149 // "oneOf" will traverse all following loaders until one will
150 // match the requirements. When no loader matches it will fall
151 // back to the "file" loader at the end of the loader list.
152 oneOf: [
153 // "url" loader works just like "file" loader but it also embeds
154 // assets smaller than specified size as data URLs to avoid requests.
155 {
156 test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
157 loader: require.resolve('url-loader'),
158 options: {
159 limit: 10000,
160 name: 'media/[name].[hash:2].[ext]',
161 },
162 },
163 // Process JS with Babel.
164 {
165 test: /\.(js|jsx|mjs)$/,
166 include: paths.appSrc,
167 loader: require.resolve('babel-loader'),
168 options: {
169
170 compact: true,
171 },
172 },
173 // The notation here is somewhat confusing.
174 // "postcss" loader applies autoprefixer to our CSS.
175 // "css" loader resolves paths in CSS and adds assets as dependencies.
176 // "style" loader normally turns CSS into JS modules injecting <style>,
177 // but unlike in development configuration, we do something different.
178 // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
179 // (second argument), then grabs the result CSS and puts it into a
180 // separate file in our build process. This way we actually ship
181 // a single CSS file in production instead of JS code injecting <style>
182 // tags. If you use code splitting, however, any async bundles will still
183 // use the "style" loader inside the async code so CSS from them won't be
184 // in the main CSS file.
185 {
186 test: /\.css$/,
187 loader: ExtractTextPlugin.extract(
188 Object.assign(
189 {
190 fallback: {
191 loader: require.resolve('style-loader'),
192 options: {
193 hmr: false,
194 },
195 },
196 use: [
197 {
198 loader: require.resolve('css-loader'),
199 options: {
200 importLoaders: 1,
201 minimize: true,
202 sourceMap: shouldUseSourceMap,
203 },
204 },
205 {
206 loader: require.resolve('postcss-loader'),
207 options: {
208 // Necessary for external CSS imports to work
209 // https://github.com/facebookincubator/create-react-app/issues/2677
210 ident: 'postcss',
211 plugins: () => [
212 require('postcss-flexbugs-fixes'),
213 autoprefixer({
214 browsers: [
215 '>1%',
216 'last 4 versions',
217 'Firefox ESR',
218 'not ie < 9', // React doesn't support IE8 anyway
219 ],
220 flexbox: 'no-2009',
221 }),
222 ],
223 },
224 },
225 ],
226 },
227 extractTextPluginOptions
228 )
229 ),
230 // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
231 },
232 {
233 test: /\.scss$/,
234 loader: ExtractTextPlugin.extract(
235 Object.assign(
236 {
237 fallback: {
238 loader: require.resolve('style-loader'),
239 options: {
240 hmr: false,
241 },
242 },
243 use: [
244 {
245 loader: require.resolve('css-loader'),
246 options: {
247 importLoaders: 1,
248 minimize: true,
249 sourceMap: shouldUseSourceMap,
250 modules: true,
251 localIdentName: '[name]-[local]-[hash:base64:5]', // class name 模块化定制
252 },
253 },
254 {
255 loader: require.resolve('postcss-loader'),
256 options: {
257 // Necessary for external CSS imports to work
258 // https://github.com/facebookincubator/create-react-app/issues/2677
259 ident: 'postcss',
260 plugins: () => [
261 require('postcss-flexbugs-fixes'),
262 autoprefixer({
263 browsers: [
264 '>1%',
265 'last 4 versions',
266 'Firefox ESR',
267 'not ie < 9', // React doesn't support IE8 anyway
268 ],
269 flexbox: 'no-2009',
270 }),
271 ],
272 },
273 },
274 {
275 loader: "sass-loader" // compiles Sass to CSS
276 }
277 ],
278 },
279 extractTextPluginOptions
280 )
281 ),
282 // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
283 },
284 // "file" loader makes sure assets end up in the `build` folder.
285 // When you `import` an asset, you get its filename.
286 // This loader doesn't use a "test" so it will catch all modules
287 // that fall through the other loaders.
288 {
289 loader: require.resolve('file-loader'),
290 // Exclude `js` files to keep "css" loader working as it injects
291 // it's runtime that would otherwise processed through "file" loader.
292 // Also exclude `html` and `json` extensions so they get processed
293 // by webpacks internal loaders.
294 exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
295 options: {
296 name: 'media/[name].[hash:2].[ext]',
297 },
298 },
299 // ** STOP ** Are you adding a new loader?
300 // Make sure to add the new loader(s) before the "file" loader.
301 ],
302 },
303 ],
304 },
305 plugins: [
306 // Makes some environment variables available in index.html.
307 // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
308 // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
309 // In production, it will be an empty string unless you specify "homepage"
310 // in `package.json`, in which case it will be the pathname of that URL.
311 new InterpolateHtmlPlugin(env.raw),
312 // Makes some environment variables available to the JS code, for example:
313 // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
314 // It is absolutely essential that NODE_ENV was set to production here.
315 // Otherwise React will be compiled in the very slow development mode.
316 new webpack.DefinePlugin(env.stringified),
317 // Minify the code.
318 new webpack.optimize.UglifyJsPlugin({
319 compress: {
320 warnings: false,
321 // Disabled because of an issue with Uglify breaking seemingly valid code:
322 // https://github.com/facebookincubator/create-react-app/issues/2376
323 // Pending further investigation:
324 // https://github.com/mishoo/UglifyJS2/issues/2011
325 comparisons: false,
326 },
327 mangle: {
328 safari10: true,
329 },
330 output: {
331 comments: false,
332 // Turned on because emoji and regex is not minified properly using default
333 // https://github.com/facebookincubator/create-react-app/issues/2488
334 ascii_only: true,
335 },
336 sourceMap: shouldUseSourceMap,
337 }),
338 // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
339 new ExtractTextPlugin({
340 filename: cssFilename,
341 }),
342 // Moment.js is an extremely popular library that bundles large locale files
343 // by default due to how Webpack interprets its code. This is a practical
344 // solution that requires the user to opt into importing specific locales.
345 // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
346 // You can remove this if you don't use Moment.js:
347 new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
348 ],
349 // Some libraries import Node modules but don't use them in the browser.
350 // Tell Webpack to provide empty mocks for them so importing them works.
351 node: {
352 dgram: 'empty',
353 fs: 'empty',
354 net: 'empty',
355 tls: 'empty',
356 child_process: 'empty',
357 },
358};