导入js库或在html< script>中引用它有什么区别?标签 [英] What is the difference between importing js library or reference it in html <script> tag

查看:79
本文介绍了导入js库或在html< script>中引用它有什么区别?标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用带有React js的Webpack.我是新手,对导入依赖项有疑问.以传统方式,我们通常从html中的< script> 标记导入第三方库.现在,我可以通过运行以下代码在javascript中完成此操作.我想知道这两种方法之间的区别是什么.是否将它们导入到相同的名称空间?还有其他区别吗?

I am currently working with webpack with react js. I am new to it and have a question about the importing dependencies. In traditional way, we usually import a third party library from the <script> tag in html. Now I can do it in the javascript by running below code. I wonder what the difference between these two approaches is. Whether they are imported into a same namespace? Is there any other difference?

import $ from 'jquery'
import React from 'react';
import ReactDOM from 'react-dom';
import load from 'little-loader';

推荐答案

您会注意到Webpack生成了一个JS文件,该JS文件通过< script> 标签.这是捆绑"文件.您在页面上总是有一个< script> 标记.

You'll notice that Webpack generates a JS file which is included via a <script> tag. This is the "bundled" file. You always have a <script> tag on the page.

什么是Webpack/Browserify/etc.他们采取了几种不同的JS文件并将它们组合为一个JS文件以通过< script> 标签加载的方法.因此:

What Webpack/Browserify/etc. do, is they take several different JS files and combine them into one JS file to load via a <script> tag. So this:

<script src="jquery.js" type="text/javascript"></script>
<script src="app.js" type="text/javascript"></script>

...成为这个:

<script src="bundle.js" type="text/javascript"></script>

jQuery和您所有的 app.js 代码现在位于 bundle.js 文件中.Webpack还将确保一切顺序正确,以便jQuery在 app.js 代码之前运行.这就是为什么有此行:

jQuery and all your app.js code is now inside the bundle.js file. Webpack will also make sure that everything is in the right order, so that jQuery runs before the app.js code. That's why you have this line:

import $ from 'jquery'

...或在ECMAScript 5中:

...or in ECMAScript 5:

var $ = require('jquery');

这告诉捆绑程序您依赖jQuery,因此可以确保按正确顺序包括了1)和2).

This tells the bundler that you depend on jQuery, so it can make sure it is 1) included and 2) included in correct order.

这篇关于导入js库或在html&lt; script&gt;中引用它有什么区别?标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆