JS模块化——02——common.js

2023-05-16

浏览器有时候识别es5的语法,而我们写代码时写的是es6语法,所以要打包,这样能转换成es5的代码

1.commonjs基于服务端(node)应用

结合引入第三方模块小案例
在这里插入图片描述
package.json中name是包名(包名不可以有中文名以及大写字母),version是版本号

如何创建package.json
首先npm init
在这里插入图片描述这里可以更改包名,也可以默认,直接回车,一路敲回车

3.下载第三方模块
npm install uniq --save
4.模块化编码

目录结构如下:
在这里插入图片描述module1.js

// module.exports=value 暴露一个对象
module.exports={
  msg:'module1',
  fn:function(){
    console.log('module1');
  }
}

module2.js

//暴露一个函数module.exports=function(){}
module.exports=function(){
  console.log("module2");
}
//这里不能再写module.exports暴露了,不然会覆盖上面暴露的

module3.js

//exports.xxx=value
exports.foo=function(){
  console.log('module3');
}
exports.bar=function(){
  console.log('bar module3');
}
exports.arr=[1,2,3,5,5,4,4,7,2,11]

app.js

//当引入第三方库时要放在自定义库前面
let uniq=require('uniq')
//将其他的模块汇集到主模块
let module1 = require("./modules/module1.js");
let module2 = require("./modules/module2.js");
let module3 = require("./modules/module3.js");
module1.fn()
module2()
module3.foo()
module3.bar()
console.log(uniq(module3.arr));

2.commonjs基于浏览器端应用

在这里插入图片描述在这里插入图片描述
创建好js文件和html文件后,npm init创建package.json
然后全局和局部都要下载broserify
下载之后编写代码后,在index.html中引入app.js
打包处理js
在这里插入图片描述
这时候dist中会有
在这里插入图片描述
在之前的Index.html中将引入的app.js改为打包好的文件bundle.js,这样就能在浏览器中运行了

目录结构如下图:
在这里插入图片描述module1.js

module.exports={
  msg:'www',
  fn:function(){
    console.log('module1');
  }
}

module2.js

module.exports=function(){
  console.log('module2');
}
module3.js
exports.foo=function(){
  console.log('module3');
}
exports.bar=function(){
  console.log("module3 bar");
}

app.js

let module1=require('./module1.js')
let module2=require('./module2.js')
let module3 = require("./module3.js");
module1.fn()
module2()
module3.foo()

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script src="./js/dist/bundle.js"></script>
</body>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JS模块化——02——common.js 的相关文章

  • Latex 表格整体居中(含实例)

    方法一 xff1a 用 begin center 和 end center 来将表格整体居中 xff0c 但它的居中只是居中了 begin table end table 如果 begin table end table 里面嵌套了 xff
  • Python三目运算符(三元运算符)用法详解(含Python代码)

    一 前言 三目运算符 xff0c 又称条件运算符 xff0c 是计算机语言 xff08 c c 43 43 java等 xff09 的重要组成部分 它是唯一有3个操作数的运算符 xff0c 有时又称为三元运算符 定义 xff1a 对于条件表
  • Anaconda安装及配置(详细版)

    1 前言 第一次下载Anaconda往往会出现一些问题 xff0c 比如不知道如何下载 xff0c 或者下载过慢等问题 xff0c 由此本文给出以下解决放方案 xff0c 并给出图示解决 2 下载anaconda 首先下载anaconda
  • 【Python】计算程序运行时间的方法总结

    一 第一种方法 利用time包 xff1a span class token keyword import span time span class token keyword def span span class token funct
  • SQLITE3 使用总结(3~5)(转)

    3 不使用回调查询数据库 34 Z6 b L 34 A 39 i8 M w d 96 T6 F H m2 上面介绍的 sqlite3 exec 是使用回调来执行 select 操作 还有一个方法可以直接查询而不需要回调 但是 xff0c 我

随机推荐