javascript - Using Webpack to require revealing modules -
i've started looking fancy stuff javascript has offer webkit
. i've got decent sized application uses revealing module pattern. these modules make calls public functions of other modules make calculations , return results.
using pattern working great until started contemplate having dozens of script includes in html pages. so, here are...
for purposes of question, have made simpler application demonstrate going wrong me.
i have 2 javascript modules contained within own files:
// one.js require("babel-loader?two!./two.js"); var 1 = (function(){ two.sayhello(); })() // two.js var 2 = (function(){ var sayhello = function(){ console.log('hello world'); } return { sayhello: sayhello } })()
what i'm trying use sayhello
function two.js
within one.js
.
so, firstly, installed webpack
, exports-loader
, created following configuration file:
module.exports = { entry: './index.js', output: { path: __dirname, filename: 'bundle.js' }, module: { loaders: [ { test: /\.jsx$/, loader: "babel-loader", query: { presets: ['es2015'] } } ] } }
index.js
entry file , includes following single line:
require('./one.js');
now, when trying run code, i'm getting following error in console:
uncaught referenceerror: 2 not defined
with little more digging, found compiled bundle.js
file throwing following error when trying import two.js
:
throw new error("module parse failed: \testing_env\webpack\two.js 'import' , 'export' may appear @ top level (2:2)\nyou may need appropriate loader handle file type.
obviously i'm doing wrong, i'm not sure what. i've tried both exports-loader
, babel-loader
no joy.
which loader should using parse module dependencies?
any appreciated.
out of box webpack has support commonjs (which same module system nodejs implements). means need use require/export syntax make use of modules.
to export in module do:
// a.js function a() { console.log("i'm module '); } module.exports = a;
and in other module do:
// b.js const = require('./a.js'); a(); // i'm module
require()
returns exports
object. whatever put on able retrieve in module.
this why webpack module bundler, comes built in module system. revelaing module pattern more practical if load js files directly in browser without module bundler, , want incapsulate data (in "modules").
the revelaing module pattern useful when don't have module system , load js files in browser. till recenlty when es modules introduced in browser, javascript didn't have module system of it's own. why people came module pattern, have way incapsulate logic in browser. because of tools webpack , have natively es modules system, can have more better way incapsulate our logic.
does make sense?
Comments
Post a Comment