简体   繁体   中英

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 (ie 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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM