標籤:regex 相對 config hunk div common try 檔案的 source
零、入口與輸出
//對像文法
entry: {
aa: __dirname + ‘/src/aa.js‘, //(chunkName :path)
bb: __dirname + ‘/src/bb.js‘
},
output: {
filename: ‘[name]-[hash].js‘,
path: __dirname + ‘/dist‘
}
//單入口
entry: ‘./src/aa.js‘,
output: {
filename: ‘bundle.js‘,
path: __dirname + ‘/dist‘ //絕對路徑(__dirname為檔案所在目錄的絕對路徑)
}
//數組
entry: [ ‘./src/aa.js‘ , ‘./src/bb.js‘],
output: {
filename: [變數] + ‘.js‘,
path: __dirname + ‘/dist‘
}
一、提取公用代碼
plugins:[ new webpack.optimize.CommonsChunkPlugin({
name: ‘common‘,
filename: ‘aa.js‘, //忽略則以name為輸出檔案的名字,否則以此為輸出檔案名字
chunks: [‘aa‘, ‘bb‘],
minChunks: true
})
]
name 或者 names:建立的chunk的名稱,如果是 names 數組,則相當於為數組裡的每個chunk 執行個體化外掛程式;
filename:輸出的 chunk的檔案名稱;
chunks:這是一個元素為 chunk.name的數組,外掛程式將會從這些 chunks 裡提取 common chunks(若忽略,所有chunk都被選擇);
minSize:非必填,common chunk 的檔案大小至少有 minSize 才會被建立;
minChunks:至少有minChunks個 chunk 共有的代碼 才會被提取(Infinity:chunk裡引用的模組不會被提取;true:chunk裡的所有公用部分都會提取);
(若想將css從common chunk中 提取出單獨的css檔案:
loaders:[{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: ‘style-loader‘,
use: ‘css-loader‘
})
},...]
plugins:[
new ExtractTextPlugin({ filename: ‘[name].css‘, allChunks: true }),
]
)
二、載入器
module: {
loaders: [ {
test: /\.js$/, loader: ‘babel-loader‘, //必須加‘-loader’
exclude: /node_modules/,
query: { presets: [‘es2015‘] }
},{
test: /\.css$/,
loader: ‘style-loader!css-loader‘
},{
test: /\.scss$/,
loader: ‘style-loader!css-loader!sass-loader?sourceMap=true!postcss-loader‘ //我們需要在js檔案裡,通過require的方式來引入css,需要安裝css-loader,
style-loader(安裝style-loader的目的是為了在html中以style的方式嵌入css)。
} ]
}
三、HTML自動引用 JS/CSS
安裝 npm install --save-dev html-webpack-plugin
plugins: [ new HtmlWebpackPlugin({
filename: ‘views/list.html‘,
template: ‘src/modules/app/list/index.html‘,
chunks: [‘common‘, ‘List‘],
hash: true}), ]
/**
*filename - 輸出檔案名,相對路徑output.path* template - HTML模板,相對設定檔目錄* chunks - 只包含指定的檔案(打包後輸出的JS/CSS),不指定的話,它會包含產生的所有js和css檔案* excludeChunks - 排除指定的檔案(打包後輸出的JS/CSS),比如:excludeChunks: [‘dev-helper‘]* hash
**/
四、自動添加相容首碼(使用postcss的autoprefixer外掛程式)
plugins: [ new webpack.LoaderOptionsPlugin({ options: { postcss: function(){ return [ require("autoprefixer")({ browsers: [‘ie>=8‘,‘>1% in CN‘] , //([‘Android >= 2.3‘,‘ios>=7‘])
cascade: true, //美化屬性值(冒號對齊) }) ] } } })
也可以配置 postcss.config.js 而不寫在plugins裡:
module.exports = { plugins: [ require(‘autoprefixer‘)({ /* ...options */ }) ]}
或直接使用autoprefixer-loader:
loaders: [{ test: /\.css$/, loader: ‘style-loader!css-loader!autoprefixer-loader?{browsers:["last 2 version", "android>=2.3"]}‘,//...}]
五、自動重新整理
安裝 npm install --save-dev webpack-dev-server
配置
devServer: { contentBase: "./public", //本機伺服器所載入的頁面所在的目錄 //colors: true, //終端中輸出結果為彩色(新版本已取消該屬性) historyApiFallback: true, //不跳轉 inline: true, //即時重新整理 port : ‘8008‘ //預設8080 }
命令:
webpack-dev-server --inline
六、Source Map
devtool: ‘eval-source-map‘ //開發環境 devtool: ‘source-map‘ //生產環境//具體原理待研究
webpack 小記