模块化

时间:2021-05-09 11:22:45   收藏:0   阅读:28

模块化

1.模块化相关规范

1.1.模块化概述

传统开发模式的主要问题

通过模块化解决上述问题

1.2.浏览器段模块化规范

1.3.服务器端模块化规范

1.3.1.CommonJS

1.4.大一统的模块化规范-ES6模块化

在ES6模块化规范诞生之前,Javascript社区已经尝试并提出AMD,CMD,CommonJS等模块化规范

但是,这些社区提出的模块化标准,还是存在一定的差异性和局限性,并不是浏览器和服务器通用的模块化标准,例如:

因此,ES6语法规范中,在语言层面上定义了ES6模块化规范,是浏览器和服务器通用的模块化开发规范

ES6模块化规范中定义:

1.4.1.Node.js中通过babel体验ES6模块化

  1. npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node【安装依赖包】

  2. npm install --save @babel/polyfill

  3. 项目根目录创建文件babel.config.js

  4. babel.config.js文件内容如下:

    const presets = [
      [
           ‘@babel/env‘,{
               targets:{
                   edge:"17",
                   firefox:"60",
                   chrome:"67",
                   safari:"11.1"
              }
          }
      ]
    ]
    ?
    module.exports = {presets}

     

  5. 通过npx babel-node index.js

报错:

PS D:\studyfile\autodidact\Vue\02-Vue02\1.babe-study> npx babel-node .\index.js
D:\studyfile\autodidact\Vue\02-Vue02\1.babe-study\node_modules\@babel\core\lib\config\validation\options.js:137
  throw unknownOptErr;
  ^
?
Error: Unknown option: .preset. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.
  at throwUnknownError (D:\studyfile\autodidact\Vue\02-Vue02\1.babe-study\node_modules\@babel\core\lib\config\validation\options.js:135:27)
  at D:\studyfile\autodidact\Vue\02-Vue02\1.babe-study\node_modules\@babel\core\lib\config\validation\options.js:120:5
  at Array.forEach (<anonymous>)
  at validateNested (D:\studyfile\autodidact\Vue\02-Vue02\1.babe-study\node_modules\@babel\core\lib\config\validation\options.js:96:21)
  at validate (D:\studyfile\autodidact\Vue\02-Vue02\1.babe-study\node_modules\@babel\core\lib\config\validation\options.js:87:10)
  at D:\studyfile\autodidact\Vue\02-Vue02\1.babe-study\node_modules\@babel\core\lib\config\config-chain.js:190:34
  at cachedFunction (D:\studyfile\autodidact\Vue\02-Vue02\1.babe-study\node_modules\@babel\core\lib\config\caching.js:52:27)
  at cachedFunction.next (<anonymous>)
  at evaluateSync (D:\studyfile\autodidact\Vue\02-Vue02\1.babe-study\node_modules\gensync\index.js:251:28)
  at sync (D:\studyfile\autodidact\Vue\02-Vue02\1.babe-study\node_modules\gensync\index.js:89:14) {
code: ‘BABEL_UNKNOWN_OPTION‘
}

解决方案:babel.config.js文件中的presets写成了preset

 

1.5.ES6模块化的基本语法

1.5.1.默认导出与默认导入

示例:

m1.js

//当前模块为m1
//外界访问不到变量d,因为他没有暴露出去
?
let a = 10;
?
let c = 20;
?
let d = 30;
?
function show(){
   console.log(111)
}
?
export default{
   a,
   c,
   show
}

index.js

//导入成员模块
import m1 from ‘./m1.js‘
?
console.log(m1)

注意:

SyntaxError: D:\studyfile\autodidact\Vue\02-Vue02\1.babe-study\m1.js: Only one default export allowed per module. (20:0)
?
18 | }
19 |
> 20 | export default{
    | ^
21 |   d
22 | }

1.5.2.按需导出与按需导入

1.5.3.直接导入并执行模块代码

就是省略了from关键字

示例:

m2.js

for (let i = 0; i < 3; i++) {
   console.log(i)    
}

index.js

import ‘./m2.js‘

 

2.Webpack

2.1当前web开发面临的困境

2.1.1.webpack概述

webpack是一个流行的前端项目构建工具(打包工具),可以处理当前web开发中所面临的问题

webpack提供了友好的模块化支持,以及代码混淆,处理js兼容问题,性能优化等强大的功能。从而让程序员把工作的重心放到具体的功能实现上,提高了开发效率和项目的可维护性

2.2.webpack的基本使用

2.2.1.在项目中安装和配置webpack

  1. 运行 npm install webpack webpack-cli -D 命令,安装webpack相关的包

  2. 在项目根目录中,创建名为webpack.config.js的webpack配置文件

  3. 在webpack的配置文件中,初始化如下基本配置

    module.exports = {
    
        //编译模式,development打包之后,代码是没有压缩的
        mode:‘development‘  //development production
    }
  4. 在package.json配置文件中的scripts节点下,新增dev脚本如下:

    "scripts": {
        "dev":"webpack"  //script节点下的脚本,可以通过npm run执行
      },
  5. 在终端中运行npm run dev命令,启动webpack进行项目打包

2.2.2.配置打包的入口和出口

webpack的默认约定:

如果要修改打包的入口和出口文件,可以在webpack.config.js中新增如下配置信息

const path = require(‘path‘)
module.exports = {

    entry:path.join(__dirname,‘./src/index.js‘), //打包的入口文件
    output:{
        path:path.join(__dirname,‘./dist‘), //输出文件的存放路径
        filename:‘bundle.js‘ //输出文件的名称

    }
}

打包中出现的问题:

> 2.webpack-study@1.0.0 dev D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study
> webpack

asset main.js 323 KiB [emitted] (name: main)
runtime modules 937 bytes 4 modules
cacheable modules 282 KiB
  ./src/index.js 143 bytes [built] [code generated]
  ./node_modules/jquery/dist/jquery.js 282 KiB [built] [code generated]
webpack 5.36.2 compiled successfully in 331 ms
PS D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study> ^C
PS D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study> ^C
PS D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study> npm run dev

> 2.webpack-study@1.0.0 dev D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study
> webpack

asset bundle.js 662 bytes [emitted] (name: main)

ERROR in main
Module not found: Error: Can‘t resolve ‘D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\.src\index.js‘ in ‘D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study‘
resolve ‘D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\.src\index.js‘ in ‘D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study‘
  using description file: D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\package.json (relative path: .)
    Field ‘browser‘ doesn‘t contain a valid alias configuration
    using description file: D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\package.json (relative path: ./.src/index.js)
      no extension
        Field ‘browser‘ doesn‘t contain a valid alias configuration
        D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\.src\index.js doesn‘t exist
      .js
        D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\.src\index.js.js doesn‘t exist
      .json
        Field ‘browser‘ doesn‘t contain a valid alias configuration
        D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\.src\index.js.json doesn‘t exist
      .wasm
        Field ‘browser‘ doesn‘t contain a valid alias configuration
        D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\.src\index.js.wasm doesn‘t exist
      as directory
        D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\.src\index.js doesn‘t exist

webpack 5.36.2 compiled with 1 error in 61 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! 2.webpack-study@1.0.0 dev: `webpack`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the 2.webpack-study@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\苏六\AppData\Roaming\npm-cache\_logs\2021-05-05T08_39_35_299Z-debug.log
PS D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study> npm run dev

> 2.webpack-study@1.0.0 dev D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study
> webpack

asset bundle.js 662 bytes [compared for emit] (name: main)

ERROR in main
Module not found: Error: Can‘t resolve ‘D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\.src\index.js‘ in ‘D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study‘
resolve ‘D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\.src\index.js‘ in ‘D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study‘
  using description file: D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\package.json (relative path: .)
    Field ‘browser‘ doesn‘t contain a valid alias configuration
    using description file: D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\package.json (relative path: ./.src/index.js)
      no extension
        Field ‘browser‘ doesn‘t contain a valid alias configuration
        D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\.src\index.js doesn‘t exist
      .js
        Field ‘browser‘ doesn‘t contain a valid alias configuration
      .json
        Field ‘browser‘ doesn‘t contain a valid alias configuration
        D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\.src\index.js.json doesn‘t exist
      .wasm
        Field ‘browser‘ doesn‘t contain a valid alias configuration
        D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\.src\index.js.wasm doesn‘t exist
      as directory
        D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\.src\index.js doesn‘t exist

webpack 5.36.2 compiled with 1 error in 55 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! 2.webpack-study@1.0.0 dev: `webpack`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the 2.webpack-study@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\苏六\AppData\Roaming\npm-cache\_logs\2021-05-05T08_42_53_421Z-debug.log

解决方案:看入口文件和出口文件的路径是否正确

2.2.3.配置webpack自动打包功能

  1. 使用npm install webpack-dev-server -D命令,安装支持项目自动打包的工具

  2. 修改package.json文件中的script中的dev:改为webpack-dev-server,如下:

    "scripts": {
        "dev": "webpack-dev-server"
      }
  3. 将src中的index.html中的script引用路径改为/bundle.js

  4. 运行npm run dev命令,重新打包

  5. 在浏览器中访问:http://localhost:8080/地址,查看自动打包效果

 

注意:

 

webpack编译遇到的问题:Error: Cannot find module ‘webpack-cli/bin/config-yargs‘ - JaceyKan - 博客园 (cnblogs.com)

 

报错原因:是因为webpack-cli和webpack的版本不匹配的原因

2.2.4.配置html-webpack-plugin生成预览页面

  1. 运行npm install html-webpack-plugin -D命令,安装生成预览页面的插件

  2. 修改webpack.config.js文件,添加如下信息:

    //导入生成预览页面的插件,得到一个构造函数
    const HtmlWebpackPlugin = require(‘html-webpack-plugin‘)
    const htmlPlugin = new HtmlWebpackPlugin({ // 创建插件的实例对象
        template:‘./src/index.html‘, //指定要用到的模板文件
        filename:‘index.html‘ //指定生成的文件的名称,该文件存在于内存中,在目录中不显示
    
    })
  3. 修改webpack.config.js文件向外暴露的配置对象,新增如下配置节点:

    module.exports = {
        plugins:[htmlPlugin] //plugins数组是webpack打包期间会用到的一些插件列表
    
    } 

 

2.2.5.配置自动打包相关的参数

//packge.json中的配置
// --open: 打包完成之后自动打开浏览器
//--host:配置IP地址
//--port:配置端口
{
    "dev": "webpack-dev-server --open --host 127.0.0.1 --port 8888"
  },

 

2.3.webpack中的加载器

2.3.1.通过loader打包非js模块

在实际开发中,webpack默认只能打包处理以.js后缀名结尾的模块,其他非.js后缀名结尾的模块,webpack默认处理不了,需要调用loader加载器才可以正常打包,否则会报错

loader加载器可以协助webpack打包处理特定的文件模块,比如:

loader的调用过程

技术分享图片

2.4webpack中的加载器的基本使用

报错提示:

ERROR in ./src/css/1.css 1:3
Module parse failed: Unexpected token (1:3)
You may need an appropriate loader to handle this file 
type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders   
> li {
|     list-style: none;
| }

报错原因:是因为webpack默认只能处理.js的文件,处理.css的文件需要使用对应的加载器来处理

2.4.1.打包处理css文件

  1. 运行 npm install style-loader css-loader -D命令,安装处理css的文件的loader

  2. 在webpack.config.js的module-->rules数组中,添加loader规则如下:

        module:{
            rules:[
                {
                    test:/\.css$/,use:[‘style-loader‘,‘css-loader‘]
                }
            ]
        }

     

其中,test表示匹配的文件类型,use表示对应要调用的loader

注意:

2.4.2.打包处理less文件

  1. 运行npm install less-loader -D命令安装处理less文件的loader

  2. 在webpack.config.js的module-->rules数组中,添加loader规则如下:

错误提示:

ERROR in ./src/css/1.less (./node_modules/css-loader/dist/cjs.js!./node_modules/less-loader/dist/cjs.js!./src/css/1.less)
Module build failed (from ./node_modules/less-loader/dist/cjs.js):
TypeError: this.getOptions is not a function
    at Object.lessLoader (D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\node_modules\less-loader\dist\index.js:21:24)
 @ ./src/css/1.less 2:12-130 9:17-24 13:15-22
 @ ./src/index.js

错误原因:是因为less-loader的版本过高,使用npm uninstall less-loader命令卸载,再使用npm install less-loader@5.0.0命令安装低版本【建议5.0.0】

 

错误提示:

ERROR in ./src/css/1.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./src/css/1.scss)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
Error: Node Sass version 5.0.0 is incompatible with ^4.0.0.
    at getRenderFuncFromSassImpl (D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\node_modules\sass-loader\dist\index.js:165:13)
    at Object.loader (D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\node_modules\sass-loader\dist\index.js:79:18)
 @ ./src/css/1.scss 2:12-130 9:17-24 13:15-22
 @ ./src/index.js

错误原因:是因为node-sass版本过高,降低版本即可,使用npm uninstall node-sass卸载已安装的版本。安装如下版本:npm install node-sass@4.14.1

2.4.4.配置postcss自动添加css的兼容前缀

  1. 运行npm install postcss-loader autoprefixer -D命令

  2. 在项目根目录中,创建postcss的配置文件,postcss.config.js,并初始化如下配置:

    const autoprefixer = require(‘autoprefixer‘) //导入自动加前缀的插件
    
    
    module.exports = {
        plugins:[autoprefixer] //挂载插件
    }
  3. 在webpack.config.js的module-rules数组中,修改css的loader规则:

        module:{
            rules:[
                {
                    test:/\.css$/,use:[‘style-loader‘,‘css-loader‘,‘postcss-loader‘]
                }
        }

     

2.4.5.打包样式表中的图片和字体文件

webpack默认处理不了合适的路径,就会报如下的错误:

ERROR in ./src/image/top.jpg 1:0
Module parse failed: Unexpected character ‘?‘ (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
 @ ./src/css/1.css (./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/dist/cjs.js!./src/css/1.css) 4:0-61 6:73-102
 @ ./src/css/1.css
 @ ./src/index.js
  1. 运行npm install url-loader file-loader -D 命令,其中file-loader是url-loader的内置依赖项

  2. 在webpack.config.js的module->rules数组中,添加loader规则如下:

        module:{
            rules:[
                {
                    test:/\.jpg|png|gif|bmp|ttf|eot|svg|woff|woff2$/,use:‘url-loader?limit=115147‘
                }
            ]
        }

    其中,?之后是loader的参数项

    limit用来指定图片的大小,单位是字节(byte),只有小于limit大小的的图片,才会被转为base64

2.4.6.打包处理js文件中的高级语法

  1. 安装babel转换器相关的包:npm install babel-loader @babel/core @babel/runtime -D

  2. 安装babel语法插件相关的包:npm install @babel/preset-env @babel/plugin-transform-runtime @babel/plugin-proposal-class-properties -D

  3. 在根目录中,创建babel的配置文件babel.config.js并初始化基本配置如下:

    module.exports = {
        presets : [‘@babel/preset-env‘],
        plugins : [‘@babel/plugin-tranform-runtime‘,‘@babel/plugin-propsal-class-properties‘] 
    
    }

     

  4. 在webpack.config.js的module->rules数组中,添加loader规则如下:

    //exclude为排除项,表示babel-loader不需要处理node_modules中的js文件
    {
        test:/\.js$/,use:‘babel-loader‘,exclude:/node_modules/
    }

     

3.Vue单文件组件

3.1.Vue单文件组件的基本用法

单文件组件的结构

3.2.webpack中配置vue组件的加载器

  1. 运行npm install vue-loader vue-template-compiler -D命令

  2. 在webpack.config.js配置文件中,添加vue-loader的配置如下:

    const VueLoaderPlugin = require(‘vue-loader/lib/plugin‘)
    plugins:[
            new VueLoaderPlugin()], //plugins数组是webpack打包期间会用到的一些插件列表
    
        {
        	test:/\.vue$/,use:‘vue-loader‘
    	}

     

     

3.4.在webpack项目中使用Vue

  1. 运行npm install vue -S安装Vue

  2. 在src-->index.js入口文件中,通过import Vue from ‘vue‘来导入vue构造函数

  3. 创建vue的实例对象,并且指定要控制的区域

  4. 通过render函数渲染App根组件

    //1.导入vue构造函数
    import Vue from ‘vue‘
    
    //2.导入App根组件
    import App from ‘./components/App.vue‘
    
    const vm = new Vue({
        //3.指定vm区域要控制的页面区域
        el:‘#app‘,
        //4.通过render函数,把指定的组件渲染到el区域
        render:h=>h(App)
    })

     

     

3.5.webpack的打包发布

配置package.json文件配置打包命令,打包命令为npm run build:

 "scripts": {
    "build":"webpack -p"
  }

 

原文:https://www.cnblogs.com/suliull/p/14747034.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!