Webpack -- 包含配置文件作为外部资源 [英] Webpack -- include configuration file as external resource

查看:39
本文介绍了Webpack -- 包含配置文件作为外部资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着应用程序的增长,是时候从代码中删除硬编码的东西了.是时候实现正确的配置文件了.

As the applicaiton grows, it is time to remove the hard coded things from the code. Time to implement proper configuration file.

我正在考虑使用 webpack,并包含配置文件,因此我可以在 react.js 应用程序中使用它.

I am thinking to use webpack, and to include configuration file, so I can require it in react.js application.

这就是我所做的(webpack.config):

This is what I have done (webpack.config):

var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: [
  './src/app.js'
],
output: {
  path: path.join(__dirname, 'public/js'),
  filename: 'app.built.js'
},
externals: {
  'Configurator':  require('./config/config-dev.json')
},
module: {
  loaders: [
    { test: /.js$/, exclude: /node_modules/, loader: 'babel?presets[]=es2015&presets[]=react' },
    { test: /.css$/, loader: "style-loader!css-loader" }
  ]
}
 };

我的 JSON 文件:

My JSON file:

{
 "product": {
 "getProducts": "/product",
 "updateProduct": "/updateproduct",
 "deleteProduct": "/deleteproduct"
},
 "project": {
 "getProjects": "/project",
 "updateProduct": "/updateproject",
 "deleteProduct": "/deleteproject"    
}  
}

在 React 组件的其中一个组件中,我尝试了这个:

And in one of the components in React components I try this:

var MyFile = require('Configurator');

没有错误,webpack 找到了文件.在控制台我看到这个:

There is no error, webpack finds the file. In console I see this:

var MyFile = __webpack_require__(412);

但 MyFile 未定义.

But MyFile is undefined.

我做错了什么?

推荐答案

require 自动解析 JSON 文件.externals 需要一个字符串来计算,所以你需要对对象进行字符串化:

require automatically parses the JSON file. externals expects a string to evaluate, so you'll need to stringify the object:

externals: {
  'Configurator': JSON.stringify(require('./config/config-dev.json'))
},

这篇关于Webpack -- 包含配置文件作为外部资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆