命名冲突
文件依赖
模块化就是把单独的一个功能封装到一个模块(文件)中,模块之间相互隔离,但是可以通过特定的接口公开内部成员,也可以依赖别的模块
模块化开发的好处:方便代码的重用,从而提高开发效率,并且方便后期的维护
AMD
CMD
模块分为单文件模块和包
模块成员导出:module.exports和exports
模块成员导入:require(‘模块标识符‘)
在ES6模块化规范诞生之前,Javascript社区已经尝试并提出AMD,CMD,CommonJS等模块化规范
但是,这些社区提出的模块化标准,还是存在一定的差异性和局限性,并不是浏览器和服务器通用的模块化标准,例如:
AMD和CMD适用于浏览器端的JavaScript模块化
CommonJS适用于服务器端的Javascript模块化
因此,ES6语法规范中,在语言层面上定义了ES6模块化规范,是浏览器和服务器通用的模块化开发规范
ES6模块化规范中定义:
每个js文件都是一个独立的模块
导入模块成员使用import关键字
暴露模块化成员使用export关键字
npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node【安装依赖包】
npm install --save @babel/polyfill
项目根目录创建文件babel.config.js
babel.config.js文件内容如下:
const presets = [
[
‘@babel/env‘,{
targets:{
edge:"17",
firefox:"60",
chrome:"67",
safari:"11.1"
}
}
]
]
?
module.exports = {presets}
通过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
默认导出语法:export default 导出的默认成员
默认导入语法:import 接收名称 from ‘模块名称‘
示例:
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)
注意:
每个模块中,只能使用唯一的一次export default否则会报错,如,我我把刚才的d导出一次:则会报错如下错误:
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 | }
如果一个模块没有导出任何东西,则导入会得到一个空对象
按需导出语法:export let s1 = ‘aaa‘;
示例:
export let s1 = ‘aaa‘;
export let s2 = ‘bbb‘;
export function say() {
console.log("ooooo")
}
按需导入语法:import {s1} from ‘模块标识符‘
示例:
import m1, {s1,s2,say} from ‘./m1.js‘
注意:一个模块中可以使用多次按需导出与导入
就是省略了from关键字
示例:
m2.js
for (let i = 0; i < 3; i++) {
console.log(i)
}
index.js
import ‘./m2.js‘
文件依赖关系错综复杂
静态资源请求效率低
模块化支持不友好
浏览器对高级JavaScript特性兼容程度较低
webpack是一个流行的前端项目构建工具(打包工具),可以处理当前web开发中所面临的问题
webpack提供了友好的模块化支持,以及代码混淆,处理js兼容问题,性能优化等强大的功能。从而让程序员把工作的重心放到具体的功能实现上,提高了开发效率和项目的可维护性
运行 npm install webpack webpack-cli -D 命令,安装webpack相关的包
在项目根目录中,创建名为webpack.config.js的webpack配置文件
在webpack的配置文件中,初始化如下基本配置
module.exports = { //编译模式,development打包之后,代码是没有压缩的 mode:‘development‘ //development production }
在package.json配置文件中的scripts节点下,新增dev脚本如下:
"scripts": { "dev":"webpack" //script节点下的脚本,可以通过npm run执行 },
在终端中运行npm run dev命令,启动webpack进行项目打包
webpack的默认约定:
打包的入口文件为src -> index.js
打包的出口文件为dist -> main.js
如果要修改打包的入口和出口文件,可以在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
解决方案:看入口文件和出口文件的路径是否正确
使用npm install webpack-dev-server -D命令,安装支持项目自动打包的工具
修改package.json文件中的script中的dev:改为webpack-dev-server,如下:
"scripts": { "dev": "webpack-dev-server" }
将src中的index.html中的script引用路径改为/bundle.js
运行npm run dev命令,重新打包
在浏览器中访问:http://localhost:8080/地址,查看自动打包效果
注意:
webpack-dev-server会启动一个实时打包的http服务器
webpack-dev-server打包生成的输出文件默认放到了项目的根目录中,是看不见,虚拟的
报错提示
internal/modules/cjs/loader.js:883 throw err; ^ Error: Cannot find module ‘webpack/bin/config-yargs‘ Require stack: - D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\node_modules\webpack-dev-server\bin\webpack-dev-server.js at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15) at Function.Module._load (internal/modules/cjs/loader.js:725:27) at Module.require (internal/modules/cjs/loader.js:952:19) at require (internal/modules/cjs/helpers.js:88:18) at Object.<anonymous> (D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\node_modules\webpack-dev-server\bin\webpack-dev-server.js:56:1) at Module._compile (internal/modules/cjs/loader.js:1063:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10) at Module.load (internal/modules/cjs/loader.js:928:32) at Function.Module._load (internal/modules/cjs/loader.js:769:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) { code: ‘MODULE_NOT_FOUND‘, requireStack: [ ‘D:\\studyfile\\autodidact\\Vue\\02-Vue02\\2.webpack-study\\node_modules\\webpack-dev-server\\bin\\webpack-dev-server.js‘ ] }
报错原因:是因为webpack和webpack-dev-server的版本不匹配的原因
报错提示:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema. - configuration has an unknown property ‘mode‘. These properties are valid: object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node?, output?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? } For loader options: webpack 2 no longer allows custom properties in configuration. Loaders should be updated to allow passing options via loader options in module.rules. Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader: plugins: [ new webpack.LoaderOptionsPlugin({ // test: /\.xxx$/, // may apply this only for some modules options: { mode: ... } }) ]
报错原因:是因为
实际上出错信息已经说明了问题原因:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
这一段的意思是webpack.config.js错误,原因是这个配置文件的版本和我们当前安装的webpack的版本不匹配。
configuration.module has an unknown property ‘loaders’.
接下来这段我们只需要看前面一句,意思是webpack.config.js这个配置文件里的module属性有一个未知的配置项loaders,原因嘛,就是我们当前安装的webpack版本已经去掉了这个配置。
报错提示:
internal/modules/cjs/loader.js:883 throw err; ^ Error: Cannot find module ‘webpack-cli/bin/config-yargs‘ Require stack: - D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\node_modules\webpack-dev-server\bin\webpack-dev-server.js at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15) at Function.Module._load (internal/modules/cjs/loader.js:725:27) at Module.require (internal/modules/cjs/loader.js:952:19) at require (internal/modules/cjs/helpers.js:88:18) at Object.<anonymous> (D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\node_modules\webpack-dev-server\bin\webpack-dev-server.js:65:1) at Module._compile (internal/modules/cjs/loader.js:1063:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) { code: ‘MODULE_NOT_FOUND‘, requireStack: [ ‘D:\\studyfile\\autodidact\\Vue\\02-Vue02\\2.webpack-study\\node_modules\\webpack-dev-server\\bin\\webpack-dev-server.js‘ ] }
报错原因:是因为webpack-cli和webpack的版本不匹配的原因
运行npm install html-webpack-plugin -D命令,安装生成预览页面的插件
修改webpack.config.js文件,添加如下信息:
//导入生成预览页面的插件,得到一个构造函数 const HtmlWebpackPlugin = require(‘html-webpack-plugin‘) const htmlPlugin = new HtmlWebpackPlugin({ // 创建插件的实例对象 template:‘./src/index.html‘, //指定要用到的模板文件 filename:‘index.html‘ //指定生成的文件的名称,该文件存在于内存中,在目录中不显示 })
修改webpack.config.js文件向外暴露的配置对象,新增如下配置节点:
module.exports = { plugins:[htmlPlugin] //plugins数组是webpack打包期间会用到的一些插件列表 }
错误提示
> 2.webpack-study@1.0.0 dev D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study > webpack-dev-server v-server.js:94:16) at D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\node_modules\webpack-dev-server\bin\webpack-dev-server.js:166:v-server.js:94:16)3 3 at D:\studyfile\autodidact\Vue\02-Vue02\2.webpack-study\node_modules\webpack-dev-server\lib\utils\processOptions.js:33:9:9 at processTicksAndRejections (internal/process/task_queues.js:93:5) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! 2.webpack-study@1.0.0 dev: `webpack-dev-server` 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-07T03_28_06_929Z-debug.log
解决方案把html-webpack-plugin的版本换一个,建议4.5.1,命令为npm install html-webpack-plugin@4.5.1
//packge.json中的配置 // --open: 打包完成之后自动打开浏览器 //--host:配置IP地址 //--port:配置端口 { "dev": "webpack-dev-server --open --host 127.0.0.1 --port 8888" },
在实际开发中,webpack默认只能打包处理以.js后缀名结尾的模块,其他非.js后缀名结尾的模块,webpack默认处理不了,需要调用loader加载器才可以正常打包,否则会报错
loader加载器可以协助webpack打包处理特定的文件模块,比如:
less-loader可以打包处理.less相关的文件
sass-loader可以打包处理.scss相关的文件
url-loader可以打包处理css中与url路径相关的文件
loader的调用过程
报错提示:
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的文件需要使用对应的加载器来处理
运行 npm install style-loader css-loader -D命令,安装处理css的文件的loader
在webpack.config.js的module-->rules数组中,添加loader规则如下:
module:{ rules:[ { test:/\.css$/,use:[‘style-loader‘,‘css-loader‘] } ] }
其中,test表示匹配的文件类型,use表示对应要调用的loader
注意:
use数组指定的loader顺序是固定的,先配置style,再配置css
多个loader的调用顺序是:从后往前,先把.css文件交给css-loader处理,再把处理结果交给前一个loader。style发现前面没有了loader,就叫给webpack打包合并
运行npm install less-loader -D命令安装处理less文件的loader
在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
运行npm install postcss-loader autoprefixer -D命令
在项目根目录中,创建postcss的配置文件,postcss.config.js,并初始化如下配置:
const autoprefixer = require(‘autoprefixer‘) //导入自动加前缀的插件 module.exports = { plugins:[autoprefixer] //挂载插件 }
在webpack.config.js的module-rules数组中,修改css的loader规则:
module:{ rules:[ { test:/\.css$/,use:[‘style-loader‘,‘css-loader‘,‘postcss-loader‘] } }
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
运行npm install url-loader file-loader -D 命令,其中file-loader是url-loader的内置依赖项
在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
安装babel转换器相关的包:npm install babel-loader @babel/core @babel/runtime -D
安装babel语法插件相关的包:npm install @babel/preset-env @babel/plugin-transform-runtime @babel/plugin-proposal-class-properties -D
在根目录中,创建babel的配置文件babel.config.js并初始化基本配置如下:
module.exports = { presets : [‘@babel/preset-env‘], plugins : [‘@babel/plugin-tranform-runtime‘,‘@babel/plugin-propsal-class-properties‘] }
在webpack.config.js的module->rules数组中,添加loader规则如下:
//exclude为排除项,表示babel-loader不需要处理node_modules中的js文件 { test:/\.js$/,use:‘babel-loader‘,exclude:/node_modules/ }
单文件组件的结构
template:组件的模板区域
script:业务逻辑区域
style:样式区域
运行npm install vue-loader vue-template-compiler -D命令
在webpack.config.js配置文件中,添加vue-loader的配置如下:
const VueLoaderPlugin = require(‘vue-loader/lib/plugin‘) plugins:[ new VueLoaderPlugin()], //plugins数组是webpack打包期间会用到的一些插件列表 { test:/\.vue$/,use:‘vue-loader‘ }
运行npm install vue -S安装Vue
在src-->index.js入口文件中,通过import Vue from ‘vue‘来导入vue构造函数
创建vue的实例对象,并且指定要控制的区域
通过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) })
配置package.json文件配置打包命令,打包命令为npm run build:
"scripts": { "build":"webpack -p" }
原文:https://www.cnblogs.com/suliull/p/14747034.html