【问题标题】:Using modules downloaded from npm使用从 npm 下载的模块
【发布时间】:2016-09-09 07:42:31
【问题描述】:

我一直在阅读 this guide on 反应,下面的段落让我有些吃惊。

出于许多良好的技术原因 CommonJS 模块(即 npm 中的所有内容)不能在浏览器中本地使用。你需要一个 JavaScript“捆绑器”将这些模块“捆绑”到您的 .js 文件中 可以在您的网页中包含一个标签。

我的印象是我可以做类似npm install jquery 的事情,然后在我的index.html 文件中通过节点模块引用它,比如 <script src="node_modules/jquery/dist.jquery.js">

是不是这样,还是我说的不对?

【问题讨论】:

    标签: javascript node.js npm


    【解决方案1】:

    是的。你是对的。 Jquery 是一个全局模块而不是 commonjs 模块。对于使用 commonjs 模块的其他包,使用 import/export 语句,您需要像 browserify 这样的捆绑器将其捆绑到单个捆绑包中,以便在浏览器中使用它

    【讨论】:

    • 啊好的,所以如果库使用了import/export,那么您需要使用browserify 或其他一些捆绑程序!明白了
    【解决方案2】:

    正如您阅读的指南中所述,那些“捆绑者”的示例是webpack/browserify/systemjs/etc..

    这些就是所谓的“模块加载器”,它基本上在运行应用程序时将模块加载到浏览器。

    这些模块加载器有一个配置文件。

    因此,例如,如果您是 webpack,则在安装 npm install webpack 后,您需要有一个 webpack.config.js,可能如下所示:

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

    【讨论】:

    • 谢谢你!明白了,丹尼尔回答了我的问题,这就是我的困惑所在
    【解决方案3】:

    当 jquery 库被加载时,它会验证它是由 bundler/loader 还是由 script 标签导入的:

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

    【讨论】:

      猜你喜欢
      • 2017-12-10
      • 2023-03-25
      • 2020-02-16
      • 1970-01-01
      • 2021-04-12
      • 2016-11-08
      • 2015-01-28
      • 2022-01-15
      相关资源
      最近更新 更多