webpack4.x 第二节

蔚落 2022-05-28 12:11 305阅读 0赞

webpack4.x 打包初体验

在根目录下建一个src(源码)目录

在建一个dist(打包后)目录

在src下建一个入口文件,index.js

  1. // index.js
  2. var oRoot = document.querySelector("#root");
  3. oRoot.innerHTML = 'Hello World!';

在dist目录建一个index.html目录

  1. //index.html
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title></title>
  6. </head>
  7. <body>
  8. <div id="root"></div>
  9. <script type="text/javascript" src="bundle.js"></script>
  10. </body>
  11. </html>
  12. 这时我们想将index.js打成bundle.js并输出在dist目录下,我们只要在项目根目录输入一下命令即可

-

  1. webpack src/index.js --output dist/bundle.js

" class="reference-link">20180404231509946

编写webpack的配置文件

webpack.config.js

  1. module.exports = { // webpack首先需要导出一个模块
  2. // 入口配置
  3. entry:{},
  4. // 出口配置
  5. output:{},
  6. //module.rules (rules就是规则的意思)
  7. //loaders
  8. module:{},
  9. // 插件
  10. plugins:[],
  11. // 开发服务器
  12. devServer:{}
  13. };

为了实现刚刚打包成bundle.js的功能,我们配置webpack.config.js

  1. module.exports = { // webpack首先需要导出一个模块
  2. // 入口配置
  3. entry:{
  4. a:'./src/index.js'
  5. },
  6. // 出口配置
  7. output:{
  8. /*
  9. path: 整体打包出去的路径(path必须是绝对路径)
  10. __dirname是node里面提供的用来获取全局路径
  11. */
  12. path:__dirname+'/dist',
  13. filename:'bundle.js'
  14. }
  15. };
  16. 这时候只要在控制台运行 webpack 即可

或者将webpack.config.js写成这样

  1. const path = require('path'); //node系统模块
  2. module.exports = { // webpack首先需要导出一个模块
  3. // 入口配置
  4. entry:{
  5. a:'./src/index.js'
  6. },
  7. // 出口配置
  8. output:{
  9. /*
  10. path必须写成绝对路径,如果写成
  11. path.resolve(__dirname,'dist')这种形式,那么就要在上面引入
  12. const path = require('path');
  13. path 表示获取路径
  14. resolve 表示合并路成一个整个路径
  15. */
  16. path:path.resolve(__dirname,'dist'),
  17. filename:'bundle.js'
  18. }
  19. };

自定义webpack.config.js文件名,那么就要执行

webpack —config hello.config.js(自定义文件名)

如果你想运行 npm run build就执行,那么你需要把webpack —config hello.config.js写到package.json的script里面配置,如下:

  1. {
  2. "name": "webpack4",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. //需要写成如下配置
  8. "build": "webpack --config hello.config.js"
  9. },
  10. "keywords": [],
  11. "author": "",
  12. "license": "ISC",
  13. "devDependencies": {
  14. "jquery": "^3.3.1"
  15. },
  16. "dependencies": {
  17. "jquery": "^3.3.1"
  18. }
  19. }

这时候你就可以运行 npm run build 了.

消除警告,将 —mode 加入 package.json的script标签中

  1. webpack --mode development
  2. webpack --mode production 文件明显被压缩

发表评论

表情:
评论列表 (有 0 条评论,305人围观)

还没有评论,来说两句吧...

相关阅读

    相关 webpack4.x 第二

    webpack4.x 打包初体验 在根目录下建一个src(源码)目录 在建一个dist(打包后)目录 在src下建一个入口文件,index.js // in