其他分享
首页 > 其他分享> > Webpack5实战笔记----上手webpack5

Webpack5实战笔记----上手webpack5

作者:互联网

新建项目 webpackstu

mkdir webpackstu && cd webpackstu
npm init -y  //初始化npm
npm install webpack webpack-cli --save-dev  //安装webpack

基础工程目录结构为:

  webpackstu
  |- package.json
+ |- index.html
+ |- /src
+   |- index.js

 我们还需要调整 package.json 文件,以便确保我们安装包是私有的(private),并且移除 main 入口。这可以防止意外发布你的代码。

{
    "name": "webpackstu",
    "version": "1.0.0",
    "description": "",
+   "private": true,
-   "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "webpack": "^5.61.0",
      "webpack-cli": "^4.9.1"
    },
    "dependencies": {}
  }

 工程目录结构:

 

 各个模块的功能:

//js目录下utils.js
const sum = (m, n) => {
    return (m + n)
}

const square = (m) => {
    return m * m
}
//将sum和square暴露出去
export {
    sum,
    square
}
//js目录下的api.js
//返回一个对象
const getInfo = () => {
    return {
        name: 'zy',
        age: 40
    }
}
//将getInfo暴露出去
module.exports = getInfo
//src目录下的index.js
import { sum, square } from './js/utils.js'
//利用require接受api.js里暴露的getInfo
const getInfo = require('./js/api.js')

console.log(sum(10, 20));
console.log(square(10));
console.log(getInfo());
//index.htnl
<!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>webpack尝试</title>

</head>

<body>
    //接受webpack打包后的模块代码
    <script src="./dist/main.js" type="module"></script>
</body>

</html>

 运行项目:

前提:安装Live Server插件,重启生效,功能可自行百度。

 在项目里打开终端,输入

webpack

 打包完成后进入index.html右键点击Open with Live Server即可看到效果。

运行结果:

 

 注意:直接用浏览器打开index.html会报错。

 总结:应用webpack打包会让浏览器兼容ES6语法格式,并统一管理各种依赖。

标签:index,Webpack5,getInfo,sum,webpack5,js,----,webpack,webpackstu
来源: https://blog.csdn.net/weixin_62273462/article/details/121074120