|
1 | 1 | # Code snippets for create-react-app 0.9.x
|
| 2 | +useful codes you can copy and use in webpack.monkey.js file. |
| 3 | + |
| 4 | +In real project I copy some of them in other file and use require function: |
2 | 5 |
|
3 | 6 | ## webpack plugin
|
4 | 7 |
|
@@ -29,4 +32,63 @@ function addBabelPlugins(webpackConfig, plugins) {
|
29 | 32 | babelLoader.query.plugins = (babelLoader.query.plugins || []).concat(plugins);
|
30 | 33 | }
|
31 | 34 |
|
32 |
| -``` |
| 35 | +``` |
| 36 | +## addLoader |
| 37 | +```js |
| 38 | +function addLoader(webpackConfig, loader) { |
| 39 | + webpackConfig.module.loaders.push(loader); |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +## addExclude |
| 44 | +cra use url loader for all unknown files. |
| 45 | +requirement: `findLoader` |
| 46 | +```js |
| 47 | +function addExclude(webpackConfig, regex) { |
| 48 | + const loader = findLoader(webpackConfig, function(rule) { |
| 49 | + return rule.loader === 'url' |
| 50 | + }); |
| 51 | + loader.exclude.push(regex); |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +## create extract text plugin |
| 56 | + |
| 57 | +```js |
| 58 | +const ExtractTextPlugin = require('extract-text-webpack-plugin'); |
| 59 | +const paths = require('react-scripts/config/paths'); |
| 60 | +const publicPath = paths.servedPath; |
| 61 | +const shouldUseRelativeAssetPaths = publicPath === './'; |
| 62 | +const cssFilename = 'static/css/[name].[contenthash:8].css'; |
| 63 | + |
| 64 | + |
| 65 | +const createTextExtractor = function (fallback, use) { |
| 66 | + const extractTextPluginOptions = {}; |
| 67 | + if (shouldUseRelativeAssetPaths) { |
| 68 | + extractTextPluginOptions.publicPath = Array(cssFilename.split('/').length).join('../') |
| 69 | + } |
| 70 | + |
| 71 | + return ExtractTextPlugin.extract(fallback, use, extractTextPluginOptions); |
| 72 | +}; |
| 73 | + |
| 74 | +``` |
| 75 | + |
| 76 | +## scss config |
| 77 | +requirement: `createTextExtractor` |
| 78 | + |
| 79 | +```js |
| 80 | +function getScssLoader(isDevelopment) { |
| 81 | + |
| 82 | + if (isDevelopment) { |
| 83 | + return { |
| 84 | + test: /\.scss$/, |
| 85 | + loader: 'style!css?importLoaders=1!postcss!sass' |
| 86 | + }; |
| 87 | + } |
| 88 | + return { |
| 89 | + test: /\.scss$/, |
| 90 | + loader: createTextExtractor('style', 'css?importLoaders=1!postcss!sass'), |
| 91 | + }; |
| 92 | +} |
| 93 | + |
| 94 | +``` |
0 commit comments