ES6语法特性(五)模块化、引入npm包

本文探讨了ES6的模块化特性,包括其优点、模块化规范产品如CommonJS、AMD和CMD,以及export和import的语法。通过示例展示了如何创建和导入模块。同时,讲解了如何使用babel解决浏览器兼容性问题,以及如何将模块化引入npm包,如jQuery。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ES6

模块化

模块化是指将一个大的程序文件,拆分为许多小的文件(模块),然后将小的文件组合起来。

优点
  1. 防止命名冲突
  2. 代码复用
  3. 高维护性
模块化规范产品

ES6之前本身没有模块化,社区衍生出模块化产品

CommonJS ===> NodeJS、Browserify
AMD ===> RequireJS
CMD ===> SeaJS

语法

模块功能主要有两个命令构成 export 、import

export 命令用于规定模块对外的接口
import 命令用于输入其他模块提供的功能

创建m1.js文件

export let name = 'wf';
export const say = () => {
  console.log('hello');
};

创建index.html文件

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script type="module">
      import * as m1 from './m1.js';
      console.log(m1);
    </script>
  </body>
</html>

结果:
在这里插入图片描述

export

分别暴露

export let name = 'wf';
export const say = () => {
  console.log('hello');
};

统一暴露

let name = 'wf';
const say = () => {
  console.log('hello');
};
export { name, say };

默认暴露

export default {
  name: 'wf',
  say: () => {
    console.log('hello');
  }
};

在这里插入图片描述

let name = 'wf';
const say = () => {
  console.log('hello');
};
export { name, say };

export default {
  name: 'wf',
  say: () => {
    console.log('hello');
  }
};

在这里插入图片描述

import

通用方式 import * as 别名 from 路径

      import * as m1 from './m1.js';

解构赋值
默认暴露需要使用 as 别名

      import { default as df, name, say } from './m1.js';
      console.log(df);
      console.log(name);

简便形式(只针对默认暴露)

      import m1 from './m1.js';
app.js

app.js 文件

import * as m1 from './m1.js';
console.log(m1);

index.html 引入
type="module"

    <script src="./app.js" type="module"></script>

在这里插入图片描述

babel

由于兼容性问题,需要将高版本js代码转化为兼容性较好的低版本代码
使用babel可以轻松的进行转换
安装三个工具:babel-cli babel-preset-env browserify(webpack)
在这里插入图片描述
首先使用 init 初始化 npm 包文件

 	npm init -y
安装babel工具
	npm i babel-cli babel-preset-env browserfity
编译

编译(js为源文件夹 dist/js 为目标文件夹,会自动生成)
–presets=babel-preset-env /可以单独配置babel配置文件实现

	npx babel js -d dist/js --presets=babel-preset-env

编译后对比
es6

// export let name = 'wf';
// export const say = () => {
//   console.log('hello');
// };

let name = 'wf';
const say = () => {
  console.log('hello');
};
export { name, say };

export default {
  name: 'wf',
  say: () => {
    console.log('hello');
  }
};

es5

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
// export let name = 'wf';
// export const say = () => {
//   console.log('hello');
// };

var name = 'wf';
var say = function say() {
  console.log('hello');
};
exports.name = name;
exports.say = say;
exports.default = {
  name: 'wf',
  say: function say() {
    console.log('hello');
  }
};

编译后app.js
在这里插入图片描述

browserify

app.js中 require 浏览器还是不识别,需要再次转换

	npx browserify dist/js/app.js -o dist/bundle.js

最终代码

(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict';

var _m = require('./m1.js');

var m1 = _interopRequireWildcard(_m);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

console.log(m1);
},{"./m1.js":2}],2:[function(require,module,exports){
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
// export let name = 'wf';
// export const say = () => {
//   console.log('hello');
// };

var name = 'wf';
var say = function say() {
  console.log('hello');
};
exports.name = name;
exports.say = say;
exports.default = {
  name: 'wf',
  say: function say() {
    console.log('hello');
  }
};
},{}]},{},[1]);

模块化引入npm包

jQuery
	npm i jquery

app.js

	import $ from 'jquery'; // const $ = require('jquery)
	$('body').css('background', 'red');

编译

	npx babel js -d dist/js --presets=babel-preset-env

打包

	npx browserify dist/js/app.js -o dist/bundle.js
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值