webpack工具的使用一、实现js打包1.1、创建项目testwebpack// 在文件夹 testwebpack// 初始化 package.jsonnpm init// 安装项目依赖 node_modulesnpm install webpack –save-dev1.2、创建文件夹app 和 build app:放源代码 build: 编译之后的输出路径 1.2.1、app文件夹内创建 app.js和hello.js 代码编写遵循 nodejs的 commonjs 规范// app.js// exports 导出创建的标签 hellomodule.exports = function(){ var hello = document.createElement(“div”); hello.textContent = ‘hello webpack’; return hello;}// build.js// require 引入var hello = require("./hello.js");// 将标签放到root中document.getElementById(“root”).appendChild(hello); 1.2.2、build文件夹内创建 index.html<body> <!– 根容器 –> <div id=“root”></div></body>1.3、使用 webpack进行编译,将app文件中源代码编译到build文件中// webpack 版本4 和 webpack 版本2 的写法不一样。主要注意// webpack2 app/app.js 是要编译的文件 build/bundle.js 是要输出文件 // webpack app/app.js build/bundle.js// webpack4 npx webpack app/app.js –output-filename build/bundle.js –output-path . –mode development 编译时可能出现报错:1、报错webpack不是内部命令–需要全局安装webpack & webpack-clinpm install webpack -gnpm install webpack-cli -g2、报错WARNING in configurationThe ‘mode’ option has not been set, webpack will fallback to ‘production’ for this value. Set ‘mode’ option to ‘development’ or ‘production’ to enable defaultsfor each environment.You can also set it to ’none’ to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/ERROR in multi ./app/app.js build/bundle.jsModule not found: Error: Can’t resolve ‘build/bundle.js’ in ‘E:\test\1webpack’ @ multi ./app/app.js build/bundle.js main[1]–查看安装webpack的版本,我安装的版本4,执行了webpack2的编译方法。需要执行webpack4的编译方法,不然会出错。1.4、编译完成后会在build文件中生成bundled.js文件引入到index.html 中就可以用了。<script type=“text/javascript” src=“bundle.js”></script>