利用Webpack打包最基礎的js程式碼

在使用webpack進行最基礎js程式碼打包前,首先確保本地已經安裝和node。js,安裝node。js後會自動安裝npm包管理器,以下是本機環境的驗證

利用Webpack打包最基礎的js程式碼

本地磁碟目錄下透過命令提示符進行npm init進行初始化,初始化後目錄下會出現一個package。json檔案

利用Webpack打包最基礎的js程式碼

利用Webpack打包最基礎的js程式碼

利用Webpack打包最基礎的js程式碼

接下來我們透過安裝

webpack

webpack-cli

利用Webpack打包最基礎的js程式碼

利用Webpack打包最基礎的js程式碼

新建Webpack配置檔案

webpack.config.js

檔案,它是專案執行的入口檔案

module。

exports

= {

//需要被打包的js檔案路徑及檔名

entry:

‘。/src/index。js’

output: {

//打包輸出的目標檔案的絕對路徑(其中__dirname為當前目錄的絕對路徑)

path:

__dirname

+

‘/dist’

//打包輸出的js檔名及相對於dist目錄所在路徑

filename:

‘index。js’

}

};

在專案根目錄下建立dist和src資料夾,並在src下建立一個名為index。js檔案,並在裡面透過document。write輸出一段文字

利用Webpack打包最基礎的js程式碼

透過

npx webpack

進行打包輸出到webpack。config。js中指定的輸出目錄

利用Webpack打包最基礎的js程式碼

在dist資料夾下建立一個

index.html

檔案,並引入index。js

<!

DOCTYPE

html

>

<

html

>

<

head

lang

=

“en”

>

<

meta

charset

=

“UTF-8”

>

<

title

>

webpack打包最基礎的js檔案

title

>

head

>

<

body

>

<

script

src

=

“index。js”

>

script

>

body

>

html

>

透過Visual Studio Code開啟該專案,然後執行index。html檔案

利用Webpack打包最基礎的js程式碼