UNPKG

@tuax/plugin-react

Version:

support react 18

67 lines (58 loc) 2.84 kB
const reactConfig = function (chainedConfig, env, type) { chainedConfig.module.rule('js-compile') .use('babel-loader') .tap((options) => { options.presets.push(require.resolve('@babel/preset-react')); if (env === 'DEBUG' && type !== 'dll') { options.plugins.push(require.resolve('react-refresh/babel', { paths: [process.cwd()] })); // 在启动项目文件夹下查找包 } return options; }); // TODO: 新增,这里会冲掉其他的设置, 设置.web.js 是为了兼容rn的同构 chainedConfig.resolve.extensions .add('.web.js') .add('.jsx') .add('.js'); // debug 模式下,添加 react-refresh 相关loader, 并且注入react-refresh/runtime, 但是不对dll进行注入 if (env === 'DEBUG' && type !== 'dll') { chainedConfig.module.rule('js-compile') .use('refresh-comregister-loader') .loader(require('path').resolve(__dirname, './refresh-comregister-loader')) .end() .use('refresh-loader') .loader(require('path').resolve(__dirname, './refresh-loader')) .before('babel-loader'); const entries = chainedConfig.toConfig().entry; for (const entryName in entries) { chainedConfig .entry(entryName) .prepend(require('path').resolve(__dirname, './entry-refresh-inject.js')); } // 因为entry-refresh-inject需要嵌入到入口,跑在浏览器端,因此,在这个文件中,无法使用path获取特定的runtime路径 // 因此,这里使用=环境变量,保证在注入模块可以找到正确的react-refresh/runtime chainedConfig.plugin('definePlugin').tap((args) => { // require的URL需使用 / 做目录分割符。在linux或者Mac OS上, 分隔符为 /,而在windows上,路径中的分隔符为 \\,所以需转换为统一的分隔符 /。 args[0]['process.env.reactRefreshRuntimePath'] = `"${process.cwd().replace(/\\/g, '/')}/node_modules/react-refresh/runtime"`; return args; }); } }; module.exports.clientConf = function (chainedConfig, env, config) { reactConfig(chainedConfig, env); }; module.exports.serverConf = function (chainedConfig, env, config) { reactConfig(chainedConfig, env); }; module.exports.dllConf = function (chainedConfig, env, config) { reactConfig(chainedConfig, env, 'dll'); }; module.exports.generate = (options) => { const userPkg = require(require('path').resolve(process.cwd(), './package.json')); return { dependencies: { ...(userPkg.dependencies.react ? {} : { react: '18.3.1' }), ...(userPkg.dependencies['react-dom'] ? {} : { 'react-dom': '18.3.1' }), ...(userPkg.dependencies['react-refresh'] ? {} : { 'react-refresh': '^0.14.2' }), // 强制安装到项目中,位置固定,如果安装到插件里,可能同样会被安装到项目的node_modules 里 }, }; };