webpack使用學習
webpack工具的使用
一、實現js打包
1.1、建立專案
// 初始化 package.json npm init // 安裝專案依賴 node_modules npm install webpack --save-dev
1.2、建立資料夾app 和 build
app:放原始碼
build: 編譯之後的輸出路徑
1.2.1、app資料夾內建立 app.js和hello.js
程式碼編寫遵循 nodejs的 commonjs 規範
// app.js // exports 匯出建立的標籤 hello module.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-cli npm install webpack -g npm install webpack-cli -g 2、報錯 WARNING in configuration The 'mode' option has not been set, webpack will fallback to 'production' for th is 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/concepts/mode/ ERROR in multi ./app/app.js build/bundle.js Module 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的編譯方法,不然會出錯。