webpack——使用webpack配置文件(二)

在 webpack 4 中,可以无须任何配置使用,然而大多数项目会需要很复杂的设置,这就是为什么 webpack 仍然要支持配置文件。这比在终端(terminal)中手动输入大量命令要高效的多,所以让我们创建一个取代使用 CLI 选项方式的配置文件:
在根目录下新建webpack.config.js

const path = require('path')
module.exports = {
    entry: {
        main: './src/index.js', //入口文件
    },
    output: {
        filename: 'bundle.js', //打包文件
        path: path.resolve(__dirname, 'dist')
    }
}

通过新配置文件再次执行构建,执行命令之前先删除原先生成的dist目录

npx webpack --config webpack.config.js

也可以简写为:

npx webpack
katedeMacBook-Air:lesson0523 kate$ npx webpack --config webpack.config.js
Hash: 5a37836feda64c8bbea6
Version: webpack 4.43.0
Time: 135ms
Built at: 2020-05-23 11:01:23
    Asset      Size  Chunks             Chunk Names
bundle.js  1.31 KiB       0  [emitted]  main
Entrypoint main = bundle.js
[0] ./src/index.js + 3 modules 737 bytes {0} [built]
    | ./src/index.js 137 bytes [built]
    | ./src/header.js 196 bytes [built]
    | ./src/content.js 202 bytes [built]
    | ./src/sidebar.js 202 bytes [built]

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/

执行命令后同样生成dist目录,打包的文件为bundle.js,再把index.html移到该目录下。

注:可以选择配置文件名字, 如果文件名为webpackconfig.js
执行命令:npx webpack --config webpackconfig.js

看到上面警告信息:

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/

解决方法:添加mode

const path = require('path')
module.exports = {
    //默认是 production,打包出来文件会被压缩,设置为development代码就不会被压缩
    mode: 'development',  //不设置会报警告
    entry: {
        main: './src/index.js', //入口文件
    },
    output: {
        filename: 'bundle.js', //打包文件
        path: path.resolve(__dirname, 'dist')
    }
}

NPM 脚本(NPM Scripts)
考虑到用 CLI 这种方式来运行本地的 webpack 不是特别方便,我们可以设置一个快捷方式。在 package.json 添加一个 npm 脚本(npm script):
添加了:“bundle”: “webpack”
package.json

{
  "name": "lesson0523",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "bundle": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11"
  }
}

现在,可以使用 npm run bundle 命令,来替代我们之前使用的 npx webpack命令。

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读