How to tell Webpack not to package a config file

I am using Webpack for an Angular 4 / TypeScript project and in one of my modules, I want to access a file config.json

with some values ​​that need to be configured on the server (i.e. config values ​​that can be changed at runtime, not at compile time ).

In my source, I link to this file using

let config = require('./../relative/path/config.json');

      

It works well, but webpack packages it and as a result dist

the config file values ​​end up with the rest of the file app.XXX.js

.

I tried to tag the file in webpack.common.js

(referenced by other webpack config files) by adding it to externals

, but that doesn't change anything. I was hoping that the webpack would then simply not package the file, but decompose it as it is into the directory dist

.

The question is: can I have config.json

, and I have , the webpack does not package it, but just deploys so that I can modify or replace the file on deployment instead of opening app.XXX.js

and searching for values?

+3


source to share


1 answer


The first thing to understand is that your application in a webpack is not running on the server, but in the client's browser. While this call require

looks like a call to read a file at runtime, it is really just an instruction for a web package to link the file and deliver it to the browser built into the package. The package itself serves as a regular file for the browser.

In light of this, the simple task of reading a configuration file at runtime becomes: fetching a file from the server and parsing it at runtime. Fortunately, webpack has a dedicated infrastructure to do just that: import () .

import('./../relative/path/config.json').then(config => {
  // Do something with 'config'
})

      



or if you are still using legacy JavaScript, you can use the deprecated require.ensure () .

require.ensure(['./../relative/path/config.json'], function(require) {
  let config = require('./../relative/path/config.json');
  // Do something special...
});

      

0


source







All Articles