Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

javascript - Webpack -- include configuration file as external resource

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

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

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" }
  ]
}
 };

My JSON file:

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

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

var MyFile = require('Configurator');

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

var MyFile = __webpack_require__(412);

But MyFile is undefined.

What I am doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'))
},

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...