Webpack4 配置 Output
output 屬性告訴 webpack 在哪裏輸出它所創建的 bundles,以及如何命名這些文件,默認值爲 ./dist
。基本上,整個應用程序結構,都會被編譯到你指定的輸出路徑的文件夾中。你可以通過在配置中指定一個 output
字段,來配置這些處理過程。output
是一個 object
,裏面包含一系列配置項,下面分別介紹它們。
簡單案例:( webpack.config.js )
// 1.導入的 path 模塊是什麼,它是一個 Node.js 核心模塊,用於操作文件路徑
const path = require('path');
module.exports = {
entry: './path/to/my/entry/file.js',
// 2.output 屬性接收的是一個對象屬性
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'my-first-webpack.bundle.js'
}
};
1.filename
靜態字符串
output.filename
配置輸出文件的名稱,爲string 類型。 如果只有一個輸出文件,則可以把它寫成靜態不變的:
新建一個項目,目錄如下:
|-- src
| | `-- common.js
| | `-- index.html
| `-- main.js
`-- webpack.config.js
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/main.js',
output: {
// 1.指定輸出的文件的名稱爲 bundle.js ( 默認爲main.js )
filename: 'bundle.js'
}
};
其它文件的內容與上一篇博客保持不變,或者下載源碼
webpack --mode development
打包後的輸出的結果:
|-- dist
| `-- bundle.js
|-- src
| | `-- common.js
| | `-- index.html
| `-- main.js
`-- webpack.config.js
藉助內置變量和模板
內置變量名 | 含義 |
---|---|
id | Chunk 的唯一標識,從0開始 |
name | Chunk 的名稱 |
hash | Chunk 的唯一標識的 Hash 值 |
chunkhash | Chunk 內容的 Hash 值 |
其中 hash
和 chunkhash
的長度是可指定的,[hash:8]
代表取8位 Hash 值,默認是20位。
注意 ExtractTextWebpackPlugin 插件是使用
contenthash
來代表哈希值而不是chunkhash
, 原因在於 ExtractTextWebpackPlugin 提取出來的內容是代碼內容本身而不是由一組模塊組成的 Chunk。
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/main.js',
output: {
// 1.指定輸出的文件的名稱爲 chunk 的 hash, 取10位 ( 默認爲main.js )
// []是模板符號,模板裏面使用 name 內置變量。
filename: '[hash:10].js'
}
};
webpack --mode development
打包後輸出:
|-- dist
| | `-- 2c86058500.js
|-- src
| | `-- common.js
| | `-- index.html
| `-- main.js
`-- webpack.config.js
2.chunkFilename
output.chunkFilename
配置無入口的 Chunk 在輸出時的文件名稱。 常見的會在運行時生成 Chunk 場景有:在使用 CommonChunkPlugin、使用 import('path/to/module')
動態加載等時。
chunkFilename 和 filename 使用基本一樣,內置變量也是一樣
3.path
output.path
配置輸出文件存放在本地的目錄,必須是 string 類型的絕對路徑。通常通過 Node.js 的 path
模塊去獲取絕對路徑:
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/main.js',
output: {
// 1.指定輸出的文件的名稱爲 bundle.js ( 默認爲main.js )
// filename: 'bundle.js'
filename: '[hash:10].js',
// 2. 指定輸出文件存放的目錄(默認是dist目錄)
path: path.resolve(__dirname, './dist'), // 藉助node的path模塊來拼接一個絕對路徑
}
};
4.publicPath
publicPath
配置發佈到線上資源的 URL 前綴,爲string 類型。 默認值是空字符串 ''
,即使用相對路徑。配置代碼如下:
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/main.js',
output: {
// 1.指定輸出的文件的名稱爲 bundle.js ( 默認爲main.js )
// filename: 'bundle.js'
filename: '[hash:10].js',
// 2. 指定輸出文件存放的目錄(默認是dist目錄)
path: path.resolve(__dirname, './dist'), // 藉助node的path模塊來拼接一個絕對路徑
publicPath:'https://cdn.xxxx.com/assets/'
}
};
1.
filename、chunkfilename、path、publicPath
都支持字符串模版2.
path
和publicPath
都支持字符串模版,但內置變量只有一個:hash
代表一次編譯操作的 Hash 值。