user6002037
user6002037

Reputation:

Using modules downloaded from npm

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?

Upvotes: 0

Views: 44

Answers (3)

Frank Bessou
Frank Bessou

Reputation: 652

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 **/ }

Upvotes: 1

Daniel Tran
Daniel Tran

Reputation: 6171

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

Upvotes: 1

Kesem David
Kesem David

Reputation: 2225

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'
};

Upvotes: 1

Related Questions