0

i have been reading this guide on react where the following paragraph has kind of thrown me.

For a number of good technical reasons CommonJS modules (i.e. everything in npm) cannot be used natively in the browser. You need a JavaScript “bundler” to “bundle” these modules into .js files that you can include in your web page with a tag.

I was under the impression that i could do something like npm install jquery and then in my index.html file reference this through node modules, something like <script src="node_modules/jquery/dist.jquery.js">

Is this not the case, or am I incorrect?

0

3 Answers 3

1

Yes. You are correct. Jquery is a global module not a commonjs module. For other package that use commonjs module, using import/export statement you need a bundler like browserify to bundle it into a single bundle in order to use it in browser

Sign up to request clarification or add additional context in comments.

1 Comment

ah ok, so if the library has used import/export then you need to use browserify or some other bundler! got it
1

As mentioned in the guide you read, examples for those "bundlers" are webpack/browserify/systemjs/etc..

These are what is called as "module-loaders" which basically loads the modules to the browser when running your applications.

These module-loaders have a configuration file.

So if for example yours is webpack, after you install npm install webpack you'll need to have a webpack.config.js that might look as follows:

module.exports = {
    entry: "./app/boot",
    output: {
        path: __dirname,
        filename: "./dist/bundle.js"
    },
    resolve: {
        extensions: ['', '.js', '.ts']
    },
    module: {
        loaders: [
            { test: /\.ts/,   loader: ["ts-loader"], exclude: /node_modules/ },
        ],
        preLoaders: [
        // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { test: /\.js$/, loader: "source-map-loader", exclude: ['node_modules', 'ext-*', 'lib', 'tools'] }
        ]
    },
    debug: true,
    devtool: 'source-map'
};

1 Comment

thanks man! got all that, daniel answered my question, thats where my confusion lay
1

When the jquery library is loaded, it verifies if it is being imported by a bundler/loader or by a script tag:

( function( global, factory ) {

"use strict";

if ( typeof module === "object" && typeof module.exports === "object" ) {

    module.exports = global.document ?
        factory( global, true ) :
        function( w ) {
            if ( !w.document ) {
                throw new Error( "jQuery requires a window with a document" );
            }
            return factory( w );
        };
} else {
    factory( global ); // export globally
}
} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { /** jQuery definition **/ }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.