onreadystatechange / blogs

主要记录项目中的重难点,以及如何攻克,有一定的借鉴意义,主要写在Issues
3 stars 0 forks source link

贴一个webpack配置,基于webpack2.x #4

Open onreadystatechange opened 5 years ago

onreadystatechange commented 5 years ago

虽说过时了,也还有点借鉴意义吧(强行自我安慰一波)

onreadystatechange commented 5 years ago

var webpack = require('webpack')
var path = require('path')
//将项目css抽离
var ExtractTextPlugin = require('extract-text-webpack-plugin')
//丑化压缩代码,生成sourcemap
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
//判断运行环境
var env = process.env.NODE_ENV || 'development'
//非production都为dev
var dev = env !== 'production'
//dev 定位源码
var devtool = dev ? 'cheap-module-eval-source-map' : 'source-map'
//端口号
const port = 8090;
//dev版本 react热更新
const commonToll = ['react-hot-loader/patch',
    `webpack-dev-server/client?http://localhost:${port}`,
    'webpack/hot/only-dev-server'];
//prod版本 去除热更新 多入口打包
const prodEntry = {
    'index': path.resolve(__dirname, './client/index.js'),
    'tindex': path.resolve(__dirname, './client/tindex.js'),
    'playback': path.resolve(__dirname, './client/playback.js'),
    'ppt': path.resolve(__dirname, './client/ppt.js'),
    'tindexv5':path.resolve(__dirname, './client/tindexv5.js'),
};
const devEntry = {
    'index': [
        ...commonToll,
        path.resolve(__dirname, './client/index.js'),
    ],
    'tindex':[
        ...commonToll,
        path.resolve(__dirname, './client/tindex.js')
    ],
    'playback': [
        ...commonToll,
        path.resolve(__dirname, './client/playback.js')
    ],
    'ppt':[
        ...commonToll,
        path.resolve(__dirname, './client/ppt.js')
    ],
    'tindexv5':[
      ...commonToll,
      path.resolve(__dirname, './client/tindexv5.js')
    ]
}
const entry = env === 'development' ? devEntry : prodEntry;
var config = {
  // debug: debug,
  devtool,
  entry,
  output: {
    //打包输出目录
    path: path.resolve(__dirname, (env !== 'production' && env !== 'testprod' && env !== 'tester') ? 'client/build' : 'dist/build'),
    filename: '[name].js',
    publicPath:'/build'
  },
  node: {
    fs: 'empty'
  },
  //防止将某些 import 的包(package)打包到 bundle 中,而是在运行时(runtime)再去从外部获取这些扩展依赖
  externals: {
    'ali-oss':'OSS',
    'fine-uploader':'qq' ,
    'localforage': 'localforage',
    // 'react': 'React',
    // 'react-dom': 'ReactDOM',
    'strophe':'Strophe',
     'fabric':'{fabric}',
    // 'react-bootstrap': 'ReactBootstrap',
    'cropperjs':'Cropper' ,
    // 'pdfjs-dist': '{PDFJS}'//no require
    './cptable': 'var cptable',
    '../xlsx.js': 'var _XLSX',
  },
  module: {
    // preLoaders: [
    //   {test: /\.js$/, loader: "eslint-loader", exclude: /node_modules/}
    // ],
    rules: [
      {
        test: [/\.js$/, /\.jsx$/],
        exclude: /(node_modules|bower_components)/,
        use: 'babel-loader'
      },
      //开启css modules,dev模式开启css热更新,将css打包入文件
      {
        test: /\.css$/,
        loader:env === 'development' ? ['css-hot-loader'].concat(
          ExtractTextPlugin.extract({fallback:'style-loader', use:'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'})
        ):ExtractTextPlugin.extract({fallback:'style-loader', use:'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'}),
        //排除node_modules,主要是antd不支持css modules
        exclude: /node_modules/
      },
      //node_modules css 使用ExtractTextPlugin.extract打包成外链,防止覆盖自定义css
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({ use:'css-loader'}),
        include: /node_modules/
      },
      //开启sass modules,防止css 变量全局污染,sass文件部分打包进style标签
      {
        test: /\.scss$/,
        exclude: [/node_modules/],
        use: [
          require.resolve('style-loader'),
          {
            loader: require.resolve('css-loader'),
            options: {
              modules: true,
              localIndexName:"[name]__[local]___[hash:base64:5]"
            },
          },
          {
            loader: require.resolve('sass-loader'), // compiles sass to CSS
          },
        ]
      },
      //开启less modules,防止css变量全局污染,less文件部分打包进style标签
      {
        test: /\.less$/,
        exclude: [/node_modules/],
        use: [
          require.resolve('style-loader'),
          {
            loader: require.resolve('css-loader'),
            options: {
              modules: true,
              localIndexName:"[name]__[local]___[hash:base64:5]"
            },
          },
          {
            loader: require.resolve('less-loader'), // compiles Less to CSS
          },
        ]
      },
      //img loader
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 10240
            }
          }
        ]
      },
      // //webpack 打包 mp4
      // {
      //   test: /\.(mp4)(\?.*)?$/,
      //   loader: 'file-loader',
      //   options: {
      //     name:'video/[name].[mp4]',
      //     limit:10
      //   }
      // },
      // //webpack 打包 mp3
      // {
      //   test: /\.(mp3)(\?.*)?$/,
      //   loader: 'file-loader',
      //   options: {
      //     name:'audio/[name].[mp3]',
      //     limit:10
      //   }
      // }
    ]
  },
  resolve: {
    //alias配置项通过别名来把原来导入路径映射成一个新的导入路径
    alias: {
      'react': path.join(__dirname, 'node_modules', 'react')
    },
    //导入语句没带文件后缀时,webpack会自动带上后缀去尝试访问文件是否存在
    extensions: ['.web.jsx', '.web.js', '.js', '.jsx'],
    //配置webpack去哪些目录下寻找第三方模块
    modules: ['src', 'node_modules'],
  },
  resolveLoader: {
    //自定义loader,主要执行try catch捕捉错误
    alias: {
      'node-loader': path.join(__dirname, 'webpack.loaders.node')
    }
  },
  //插件
  plugins: [
    // new webpack.HotModuleReplacementPlugin(),
    // new webpack.NamedModulesPlugin(),

    new webpack.ExternalsPlugin('commonjs', ['electron']),
    //提取css
    new ExtractTextPlugin('[name].css'),
    //忽略编译错误
    new webpack.NoEmitOnErrorsPlugin(),
    //允许你创建一个在编译时可以配置的全局常量
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(env),
      'process.env.BUILDER_OS': JSON.stringify(process.platform)
    }),
    // new webpack.SourceMapDevToolPlugin({
    //   test: [/\.js$/, /\.jsx$/],
    //   filename: '[file].map',
    //   append: false,
    //   noSources: true, // Sourcemap without source
    //   hidden: true
    // })
  ],
  //webpack开发服务器
  devServer: {
    publicPath:'/build',
    hot:true,
    proxy: {
      '/classRoom/*': {
        target: "http://localhost:8090/_redirect.html?",
        pathRewrite: {'^/classRoom/*': ''}
      },
      '/smallClassRoom/*': {
        target: "http://localhost:8090/_redirect.html?",
        pathRewrite: {'^/smallClassRoom/*': ''}
      },
      '/freeClassRoom/*': {
        target: "http://localhost:8090/_redirect_stu.html?",
        pathRewrite: {'^/freeClassRoom/*': ''}
      }
    }
  }
}

if (!dev) {
  // delete config.externals.fabric
  config.plugins.push(new UglifyJSPlugin({
      sourceMap: true,
      uglifyOptions: {
          output: {
              comments: false,
              beautify: false,
          },
          warnings: false
      }
  }))
}

module.exports = config