gpt4 book ai didi

reactjs - Webpack 主题加载器

转载 作者:行者123 更新时间:2023-12-03 13:36:48 26 4
gpt4 key购买 nike

我想完成以下结构:

  • button.core.jsx
  • button.theme-a.jsx
  • button.theme-b.jsx

以 React 为例,我想在 button.core.jsx 中执行以下操作:

import React from 'react';
import Themed from './button.[theme]';

export default class Button extends React.Component {
render() {
if (Themed) {
return <Themed />;
}
return <button>default button</button>;
}
}

换句话说,我想在我的 webpack.config.js 中定义一个主题并加载该文件(如果存在)。如果没有,则呈现默认行为。我认为这将是一个非常强大的设置!

我一直在寻找制作自定义加载程序的方法,但尚未成功。谁能指出我正确的方向?

最佳答案

我已经通过编写自定义“解析器”解决了这个问题:

const ThemeResolver = {
apply: function(resolver) {
resolver.plugin('file', function(req, cb) {
if (req.request.indexOf('[theme]') == -1) {
return cb();
}

const defaultFile = req.request.replace('[theme]', 'Default');
const themedFile = req.request.replace('[theme]', process.env.THEME);
req.request = themedFile;

this.doResolve(['file'], req, (err) => {
if (!err) {
return cb();
}
req.request = defaultFile;
this.doResolve(['file'], req, cb);
})
});
}
};

module.exports = {
// ...
plugins: [
new webpack.ResolverPlugin([ThemeResolver]),
]
// ...
};

它尝试将路径中包含 [theme] 的文件解析为主题定义为环境变量的路径。如果失败,它将回退到默认文件。这样我就可以需要一个主题文件,如下所示:

从“./button-[主题]”导入演示文稿

主要组件与我的问题有点不同,但我实际上对此非常满意:

import React from 'react';
import Presentation from './button-[theme]';

export default class Button extends React.Component {
onClick = (e) => console.log('some logic');

render() {
return <Presentation onClick={ this.onClick } />;
}
}

此按钮组件的逻辑可以位于 button.core.jsx 内部,而表示将由以下组件之一处理:

THEME=theme-a npm start // button-[theme] resolves to button-theme-a.jsx
THEME=theme-c npm start // button-[theme] resolves to button-default.jsx

免责声明:我还没有在大规模或生产环境中使用它,但它似乎可以在小型 POC 中使用。如果我做了不明智的事情,请告诉我!

关于reactjs - Webpack 主题加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35019932/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com