最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】ReactJS的Preact中如何用配置文件中参数或者全局定义的常量用于其他地方

Preact crifan 5303浏览 0评论

折腾:

【已解决】ReactJS中首页要点击3次才能加载内容

期间,现在需要:

把当前项目中的路由的前缀,从

/

/profile

之类的,统一都加上”/uapp”前缀,变成:

/uapp/

/uapp/profile

等。

且希望可以方便的配置,批量修改这个前缀。

目前项目中有三处地方:

其中:

第三处是:

src/store/store.js

是不方便用全局变量的

当然可以用全局常量或配置文件

其实最好是用配置文件的参数

preact global config

react global config

reactjs – use global config object in react app – Stack Overflow

javascript – How to store Configuration file and read it using React – Stack Overflow

javascript – Make global config available to react component – Stack Overflow

看到此处有个config.json

不知道如何利用

javascript – How can I use a config file in React? – Stack Overflow

还是用js的config文件,然后export

其他文件import即可。

preact config.json

react config.json

react config.json how use

Global Configuration Variables · Issue #446 · react-boilerplate/react-boilerplate

经过尝试

/Users/crifan/dev/dev_root/daryun/Projects/xx/src/config.json

然后结果是:

【总结】

Preact中可以借用externals的loader去解析config.json中的字符串未JSON对象,从而使得支持这种config的做法的:

(1)先给webpack.config.babel.js中加上config.js的解析:

/webpack.config.babel.js

import path from ‘path’;
module.exports = {
  externals: {
    // config: JSON.stringify(require(‘path/to/config.json’)), //eslint-disable-line
    config: JSON.stringify(path.resolve(__dirname, "src/config.json")), //eslint-disable-line
  },
}

(2)然后去定义config.json的配置(不要包括注释):

/src/config.json

{
  "routePrefix": "/uapp"
}

(3)其他地方调用config

src/store/store.js

import config from ‘../config’;
    text: `${config.routePrefix}+首页`,

效果:

【注意事项】

注意,导入的时候,要用import config,而不是 import {config}

即:

// import {config} from ‘../../../config.json’;
// import {config} from ‘../../../config’;
// import {config} from ‘~config’;

这些写法都有问题,要改为:

import config from ‘../../../config’;

才有效。

【小缺点】

config.json中,虽然编辑器可以识别//开头的注释:

但是实际上JSON.stringify调用的JSON.parse是不支持的:

ERROR in ./src/config.json
Module build failed: SyntaxError: Unexpected token / in JSON at position 4
    at JSON.parse (<anonymous>)
    at Object.module.exports (/Users/crifan/dev/dev_root/daryun/Projects/奥拓/奶牛云/sourcecode/ucowsapp/ucowsapp/node_modules/json-loader/index.js:7:48)
@ ./src/store/store.js 9:14-34
@ ./src/index.js
@ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server babel-polyfill ./index.js

所以,也没发同时存在:

  // "routePrefix": ""
  "routePrefix": "/uapp"

了。

算是个小缺点。

转载请注明:在路上 » 【已解决】ReactJS的Preact中如何用配置文件中参数或者全局定义的常量用于其他地方

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.159 seconds, using 22.15MB memory