wuye1200 / blog

alber blog
0 stars 0 forks source link

Webpack 配置详情 #5

Open wuye1200 opened 6 years ago

wuye1200 commented 6 years ago

配置

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  entry: './entry.js', //入口文件 可配置多入口
  output: {
    path: __dirname,//出口路径
    filename: 'js/[id]-[name]-[hash].js'//出口名称
  },
  //webpack插件
  plugins: [
    new HtmlWebpackPlugin({
      inject:'head',//将script标签插入到head标签中
      filename: 'index-[hash].html',//生成的html文件名称为'index.html'
    })
  ]
}
wuye1200 commented 6 years ago

entry

//方式一:单文件写法
entry: {
    index: './src/pages/route.js',
    //about: './src/pages/about.js',
    //other:()=>{...}
}

//方式二:多文件写法
entry: {
    /*index:[
        'webpack-hot-middleware/client',
        './src/root.js'
    ],*/
    index: ['./src/root.js'],
    vendors : ['react','react-dom','redux','react-router','classnames'],
}

output - 输出

output: {
    path: path.resolve(__dirname, '../assets'),
    filename: 'js/[name].js',
    chunkFilename: 'js/[name].[chunkhash:8].js',
    publicPath: '/_static_/', //最终访问的路径就是:localhost:3000/_static_/js/*.js
    //pathinfo:true,
}
wuye1200 commented 5 years ago

[插件] 可视化查询文件分布
webpack-bundle-analyzer

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
plugins: [
    new BundleAnalyzerPlugin()
]

[插件] 压缩

new HtmlWebpackPlugin({
      minify:{
          removeComments: true,//删除注释
          collapseWhitespace:true//删除空格
      }
})

[插件] 模板文件

new HtmlWebpackPlugin({
      filename: 'index-[hash].html',//生成的html文件名称为'index.html'
      template:'template/template.html'//模板文件为'template.html'
})
wuye1200 commented 5 years ago

【多页入口改造】

var glob = require('glob')
//目录输出
  function getEntry(globPath, pathDir) {
    var files = glob.sync(globPath);
    var entries = {},
      entry, dirname, basename, pathname, extname;

    for (var i = 0; i < files.length; i++) {
      entry = files[i];
      dirname = path.dirname(entry);
      extname = path.extname(entry);
      basename = path.basename(entry, extname);
      pathname = path.join(dirname, basename);
      pathname = pathDir ? pathname.replace(pathDir, '') : pathname;
      console.log(2, pathname, entry);
      entries[pathname] = './' + entry;
    }
    return entries;
  }

var htmls = getEntry('./src/app/*.js', 'src\\app\\');

var entryObj = {};
var entryPlugin = [];
var entryObjIndex =0
for (var key in htmls) {

  entryPlugin.push([
    require.resolve('./polyfills'),
    require.resolve('react-dev-utils/webpackHotDevClient'),
    paths.appSrc + '\\app\\'+key+'.js',
  ])

  entryObj[key] = entryPlugin[entryObjIndex]
  entryObjIndex++
}
【插件多入口】
for (var key in htmls) {
  var neeplugin = new HtmlWebpackPlugin({
      inject: true,
      chunks:[''+key+''],
      template:paths.appHtml,
      filename:''+key+'.html'
  })

  console.log( 444)
  console.log( neeplugin)
  module.exports.plugins.push(neeplugin)
}