Webpack--前端框架

511 阅读2分钟
ES6的使用

let/const/箭头函数/···/new/class/Promise 继承/this/原型

CSS语法和布局

MVC概念 Model/View/Controller/EventHub

工具的使用

webpack的安装

  1. 登录webpack的官网
  2. 进入DOCUMENT
  3. 进入GUIDES
  4. 进入getting started
  5. 进入Basic Setup
  6. 在VS Code中创建新文件夹
  7. 新建终端输入
  8. npm init -y
  9. 会自动创建一个文件夹package.json
  10. 再次输入yarn add webpack webpack-cli --dev
  11. 会自动创建一个node_modules

局部安装

上述步骤的操作是局部安装的webpack,就是在node_modules中安装的。 在终端中输入./node_modules/.bin/webpack --version 可以得到安装的版本号: webpack 5.44.0 webpack-cli 4.7.2 简写用npx webpack也可以查看各种相关的属性

运行时有warning

当运行npx webpack时,出现下面警告:

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

如何解决: 打开webpack网页,找到configuration,出现webpack.config.js黑色框框,在vs code中创建webpack.config.js,将黑色框里的代码复制进去。

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './foo.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'foo.bundle.js',
  },
};

因为warning中提示的只是mode,所以把其他的不想关的代码删除,只剩下面这些:

const path = require('path');


module.exports = {
  mode: 'development',
  
};

如果是正在开发中就用development; 如果是要发布了,就用production; 入口和出口的配置:

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'index.js',
  }
};

filename: '[name].[contenthash].js', } 这个就是HTTP缓存。因为每次缓存时,这种缓存文件会很多,所以要有一个删除的功能。就是在 package.json这个文件中的,添加build文件。

"scripts": {
    "build":"rm -rf dist && webpack",

所以下次运行时直接在终端输入 yarn build 或者npm run build 这样就会删除缓存文件了。

webpack生成html

在浏览器内搜索webpack create html page 回到终端内

git init //初始化一下
git status //用于显示工作目录和暂存区的状态
创建一个文件.gitignore
把不用上传的/dist/和/node_modiules/放在.gitignore里面。
再次git status,可查看是否去掉那俩文件
git add . //上传当前目录
git commit -m 'init'//提交

回到浏览器内搜索webpack create html page。 按照上面的指示来安装在installation中复制下方代码进行安装 yarn add html-webpack-plugin --dev 在Basic Usage中复制代码


const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
  entry: 'index.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'index_bundle.js',
  },
** plugins: [new HtmlWebpackPlugin()], **
};

只提取其中有用的

const HtmlWebpackPlugin = require('html-webpack-plugin');
plugins: [new HtmlWebpackPlugin()],

然后运行: yarn build 则会自动生成index.html dist文件是自动生成的,里面的文件,不能修改。

如何操作,生成的index.html里面的内容呢,自动改文件名呢?

在webpack.config.js中的

 plugins: [new HtmlWebpackPlugin(
 { title: 'My App',}
      )]  
};

添加{title:'my app'},则dist文件中自动生成的index.html中的title会变成'my app'

webpack自动引入CSS