webpack中的模块化开发

模块:指为了完成某功能所需的程序或者子程序,模块是系统中 职责单一 且 可替换 的部分

模块化:** 指把系统代码分为一系列职责单一 且 可替换的 模块

模块化开发:指如何开发新的模块和复用已有的模块来实现应用的功能

CommonJS

  1. //sayhi.js
  2. var hi = "hello"
  3. function sayHi(){
  4. return hi
  5. }
  6. module.exports = sayHi
  7. //index.js
  8. var sayHi = require("./sayhi")
  9. console.log(sayHi())


AMD**

  1. //sayhi.js
  2. define(function(){
  3. var hi = "hello";
  4. return function sayHi(){
  5. return hi
  6. }
  7. })
  8. //index.js
  9. require(['./sayHi.js'],function(sayHi){
  10. console.log(sayHi())
  11. })


ES6 Module**

  1. //sayhi.js
  2. const hi = "hello"
  3. export default function sayHi(){
  4. return hi
  5. }
  6. //index.js
  7. import sayHi from './sayhi'
  8. console.log(sayHi())



webpack中一切皆模块

image.png


webpack 对 Module的增强

  1. import('path/to/module').then(mod=>{
  2. console.log(mod)
  3. })

import from 是静态分析打包语法
import() 是动态打包语法,即通过异步的方式加载进来的

webpack对资源的模块化处理

样式文件的@import 和 javascript 的import
在css中

  1. @import 'vars.less'

在javascript中

  1. import style from './style.css'