-y 預設
npm init -y
https://webpack.js.org/concepts/#entry
--save-dev 開發環境
安裝 webpack 及 webpack-cli
npm install webpack webpack-cli --save-dev
(1) 建立資料夾src為 entry
(2) 建立資料夾dist為 output
(3)src內資料,藉由webpack編譯,輸出dist內資料(壓縮後)
npm run build
將 entry 及 output 自定義
https://webpack.js.org/concepts/#output
webpack.config.js
module.exports = {
entry: "./src/index.js",
output: {
// path.resolve 轉絕對路徑
// __dirname 當前資料夾
path: path.resolve(__dirname, "dist"), // 輸出資料夾
filename: "bundle.js", // 輸出檔案名稱
},
};
編譯
npm run build
下指令獨立執行js檔案
package.json
"scripts": {
"hihi":"node hello.js"
},
npm run hihi
package.json
"scripts": {
"dev":"webpack --mode development",
"deploy":"webpack --mode production"
},
npm run dev
npm run deploy
export default 333;
import c from './c.js'
console.log(c);
"scripts": {
"dev":"webpack --mode development",
"deploy":"webpack --mode production"
},
npm run deploy
src > index.html
<body>
<h1>標題</h1>
<script src="./bundle.js"></script>
</body>
https://github.com/webpack-contrib/css-loader
npm install --save-dev css-loader
npm install style-loader --save-dev
https://github.com/webpack-contrib/css-loader
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"], //順序不可變更 編譯會出錯
},
],
},
};
src > style.css
h1{
color: red;
}
src > index.js
import css from './style.css'
npm run deploy
成功
https://github.com/webpack-contrib/sass-loader
npm install sass-loader sass --save-dev
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
"style-loader",
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
],
},
],
},
};
import "./style.scss";
亦可引入app.js(此處引入index.js)
src > style.scss
$body-color: rgba(255, 153, 0, 0.527);
body {
background-color: $body-color;
}
npm run deploy
成功
用scss就不可以用css,否則會出錯
開啟一個伺服器,即時更新資料,就不用一直npm run
https://github.com/webpack/webpack-dev-server
npm install webpack-dev-server --save-dev
https://webpack.js.org/configuration/dev-server/
module.exports = {
//...
devServer: {
static: {
directory: path.join(__dirname, 'dist'), // 輸出路徑是哪個資料夾
},
compress: true,
port: 9000,
},
};
"scripts": {
"dev": "webpack serve --mode development",
},
編輯設定檔 webpack.config.js
增加 open:true,
devServer: {
static: {
directory: path.join(__dirname, 'dist'), // 輸出路徑是哪個資料夾
},
compress: true,
port: 9000,
open:true,
},
npm run dev
https://www.npmjs.com/package/axios
npm install webpack-dev-server --save-dev
src > index.js
import axios from "axios";
src > index.js
import axios from "axios";
axios.get("https://hexschool.github.io/ajaxHomework/data.json").then(function(response){console.log(response);})
npm run dev
太厲害了
同步加碼Webpack
不過最近因為 Vite
的出現
有可能 Webpack
會成為歷史
感謝前輩不嫌棄並且告知新資訊~~
可以順帶請教一下那個紅字是怎麼弄出來的嗎XD
你可以用 ` 把文字包住
就會變紅色的了
謝謝~