I have a single .json file that contains configuration stuff that I would like to reference from another script file using the typical import/require syntax. Currently I\'m
With Webpack 2, you can use System.import. It uses the Promise API. AFAIK, currently there's no way to have async/await code run in the browser. I believe Babel can only transpile async/await down to ES2015 so only the latest version of Node (v6.x) can run it. I don't think browsers are capable of understanding it yet because the transpiled code uses generators.
For System.import please note that some older browsers (IE 11 and below I believe) will require you to polyfill the Promise API. Check out polyfill.io for that.
If you REALLY want to use async/await in the browser, you might be able to do a full polyfill for ES2015.
I had the same case with a file (config.json).
I decided to copy it with Copy-Webpack-Plugin
new CopyWebpackPlugin([
// Copy directory contents to {output}/
{ from: 'config.json' }
])
After that, my file was in the output build directory. I used 'externals' property to reference my file in my webpack.config file :
externals: {
'config': "require('./config.json')"
}
In my js file which load the config.json :
import config from 'config'
'config' load require('./config.json) which is the one in the output build directory.
I know it's tricky but I didn't find another solution to my problem. Maybe it will help someone.
EDIT
I had to use webpack in order to build because import config from 'config'
wasn't understandable without it. That's why I replace :
externals: {
'./config.json': "require('./config.json')"
}
and
var config = require('./config.json') //replace import config from 'config'
Without webpack, Javascript understand var config = require('./config.json')
because it's the right path.
And when I build with webpack, it change by require('./config.json')
when it sees './config.json', so it works
I think what you want is require.ensure, webpack's code splitting. The modules that you 'ensure' are put into a separate bundle, and when your 'ensure' executes at runtime, the webpack runtime automatically fetches the bundle via ajax. Note the callback syntax for ensure -- your callback runs when the bundle has finished loading. You still need to require the desired modules at that point; .ensure just makes sure they're available.
Code splitting is one of webpack's major features, it lets you load only what you need at any given time. There's plugins etc. to optimize the multiple bundles as well.