🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# `webpack`结合`npm scripts` 我们后面会不断的修改项目文件,每次修改完要重新执行`webpack src/main.js -o dist/bundle.js`命令。感觉 命令比较长,比较繁琐。 ## 安装本地项目依赖 >[success] 因为一个项目往往依赖特定的webpack版本,全局的版本可能很这个项目的webpack版本不一致,导出打包出现问题。 > 所以通常一个项目,都有自己局部的webpack。 `npm install webpack webpack-cli -D` ~~~ { "name": "demo1", "version": "1.0.0", "dependencies": { "jquery": "^3.4.1" }, "devDependencies": { "webpack": "^4.35.0", "webpack-cli": "^3.3.5" } } ~~~ ## npm scripts 我们可以结合`npm scripts`来方便我们书写命令。修改`package.json`文件如下: ~~~ { "name": "demo1", "version": "1.0.0", "scripts": { "start": "webpack src/main.js -o dist/bundle.js" }, "dependencies": { "jquery": "^3.4.1" }, "devDependencies": { "webpack": "^4.35.0", "webpack-cli": "^3.3.5" } } ~~~ ## 启动命令 `npm start 或者npm run start` ## 解释 `npm run xxx` 这其中的`xxx`就是我们在scripts中定义的key值。 这样一句命令代表着我们将xxx的值执行。即执行`webpack src/main.js -o dist/bundle.js`。 这里面的`webpack`命令其实是利用的我们项目的开发环境的的`webpack-cli`模块。如果本地项目未完装`webpack`、`wepback-cli`则去找全局命令。 ## 注意 > start这个命令可以省去run其它都不可以 ## 问题 上面命令执行后是可以进行打包,不过会产生一个警告提示。按照提示添加mode属性要么为production(生产环境)或者development 开发环境 。我们在这里了解一下开发环境。所以将mode属性的值设置为development; ~~~ > demo1@1.0.0 start C:\Users\zhaoy\Desktop\react\01\demo1 > webpack src/main.js -o dist/bundle.js Hash: 4e6df5b73ef9caaba844 Version: webpack 4.35.0 Time: 329ms Built at: 2019-06-24 7:36:41 PM Asset Size Chunks Chunk Names bundle.js 87.6 KiB 0 [emitted] main Entrypoint main = bundle.js [1] ./src/main.js 106 bytes {0} [built] + 1 hidden module WARNING in configuration The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option t o '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/configurati on/mode/ ~~~ **修改npm scripts** ~~~ webpack src/main.js -o dist/bundle.js --mode development ~~~ ~~~ { "name": "demo1", "version": "1.0.0", "scripts": { "start": "webpack src/main.js -o dist/bundle.js --mode development" }, "dependencies": { "jquery": "^3.4.1" }, "devDependencies": { "webpack": "^4.35.0", "webpack-cli": "^3.3.5" } } ~~~ ## 项目源码 `git clone https://github.com/highh5/webpack.git -b lesson-02`