How to know when to import a package or paste it in index.html

后端 未结 2 1058
离开以前
离开以前 2020-12-06 07:12

OK, I am using ES6 and ReactJS, some packages you should do import React from \"react\"; in order to have them working, but others

2条回答
  •  佛祖请我去吃肉
    2020-12-06 08:06

    I came across this question in the following situation: I want to use the react and react-dom api in a script I'm writing for a local index.html file. I can put a tag in the of index.html, but I would prefer to have the apis on my local system. So I wget react-cdn-url and see if I can just import it. I get some error on the console, so I look at the react.js file I now have and see the following lines:

    (function (global, factory) {
        typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof define === 'function' && define.amd ? define(factory) :
        (global.React = factory());
    }(this, (function () { 'use strict';
    ...
    })));
    

    Once I decipher this, I should be able to make my react api "importable." So let's peel this apart bit by bit. First construct:

    (function (global,factory){}(this,(function() {...})));
    

    This is a bit confusing at first, so first look at the expression: (function (params){}(args)); The purpose of this is to create an unnamed function which takes paramaters params, then immediately call it with arguments arg. Contrast this with ;function (params){}(args);. This is not valid javascript, if you try it in node you sort of break the parser, if you do it in firefox console you'll get the error: SyntaxError: function statement requires a name. The reason why is that this is an incomplete syntactic construct. Javascript grammar allows you to write a function definition without a bound name, but this only makes sense in an expression. Enclosing the function definition in parenthesis causes it to be evaluated. Putting this all together we have an unnamed function being called on arguments this and (function(){}) (another unnamed function). this will be whatever the local context is, and the unnamed function corresponds to the factory parameter in the "top-level" anonymous function. Consider the following three lines:

    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global.React = factory());
    

    These check to see if this module is being imported from node, if so, it exports the result of the factory function. If it is being imported by require.js, it "defines" the factory function, if neither of these then the result of factory is given the name 'React' in the global object. This last case applies when "importing" the library through a

提交回复
热议问题