不使用eject,自定义webpack配置使用stylus以及alias@别名和autoprefixer前缀
- 在项目根目录下新建一个scripts文件夹。
- 在scripts文件夹中新建customized-build.js、overrides-config.base.js、overrides-config.dev.js、overrides-config.prod.js四个文件
- 安装rewire来实现运行时动态替换react-scripts // yarn add rewire proxyquire –save
- 在customized-build.js中加入以下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43var rewire = require('rewire');
var proxyquire = require('proxyquire');
switch(process.argv[2]) {
case 'start':
rewireModule('react-scripts/scripts/start.js',
loadCustomizer('./overrides-config.dev'));
break;
case 'build':
rewireModule('react-scripts/scripts/build.js', loadCustomizer('./overrides-config.prod'));
break;
default:
console.log('customized-build only supports "start", "build", and "test" options.');
process.exit(-1);
}
function loadCustomizer(module) {
try {
return require(module);
} catch(e) {
if(e.code !== "MODULE_NOT_FOUND") {
throw e;
}
}
// If the module doesn't exist, return a
// noop that simply returns the config it's given.
return config => config;
}
function rewireModule(modulePath, customizer) {
// Load the module with `rewire`, which allows modifying the
// script's internal variables.
let defaults = rewire(modulePath);
// Reach into the module, grab its global 'config' variable,
// and pass it through the customizer function.
// The customizer should *mutate* the config object, because
// react-scripts imports the config as a `const` and we can't
// modify that reference.
let config = defaults.__get__('config');
customizer(config);
}
- 在customized-build.js中加入以下代码:
- 安装poststylus,autoprefixer只是其中的一个插件,yarn add poststylus -D开发环境替换配置:stylus 和 alias(也就是vue中的@路径别名),在dev.js文件中引入以下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13const baseConfig = require('./overrides-config.base')
module.exports = function(config) {
let alias = config.resolve.alias;
alias["@"] = baseConfig.rootPath;
let loaderList = config.module.rules[1].oneOf;
loaderList.splice(loaderList.length-1, 0, {
test: /\.styl$/,
use: ["style-loader", "css-loader", "stylus-loader"]
})
config.plugins.push(baseConfig.stylusLoaderOptionsPlugin);
}
- 安装poststylus,autoprefixer只是其中的一个插件,yarn add poststylus -D开发环境替换配置:stylus 和 alias(也就是vue中的@路径别名),在dev.js文件中引入以下代码:
在base.js文件中引入以下代码:
1 | const path = require('path'); |
- 安装stylus依赖,yarn add stylus stylus-loader –save
- 还需要创建一个config-overrides.prod.js文件具有相同的内容。开发过程中使用的是dev文件(例如npm start),在构建期间使用prod文件(例如,npm run build)
- 最后,要让这些新代码生效,你需要更改package.json,调用这些新的脚本,而不是默认的react-scripts的脚本。要做到这一点,可以用以下方法替换“start”、“build”和“test”
1
2
3
4
5"scripts": {
"start": "node scripts/customized-build start",
"build": "node scripts/customized-build build",
"test": "node scripts/customized-build test --env=jsdom",
},
- 最后,要让这些新代码生效,你需要更改package.json,调用这些新的脚本,而不是默认的react-scripts的脚本。要做到这一点,可以用以下方法替换“start”、“build”和“test”
注意⚠️:每次修改配置文件都要重启一下yarn start