felix-cao / Blog

A little progress a day makes you a big success!
31 stars 4 forks source link

Webpack入门九:使用SCSS #29

Open felix-cao opened 6 years ago

felix-cao commented 6 years ago

Sass(Scss)号称是世界上最成熟、稳定和强大的专业级CSS扩展语言, Sass中文网(https://www.sass.hk/guide/)

$ npm i sass-loader node-sass postcss-loader autoprefixer -D

webpack.config.js

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: './app/main.ts',
  devtool: 'inline-source-map',
  output: {
    path: __dirname + '/dist', // 将输出放到dist文件夹
    filename: 'app-[hash].js'
  },
  devServer: {
    contentBase: './dist',
    host: '127.0.0.1',
    port: 8080,
    inline: true,
    compress: false
  },
  resolve: {
    extensions: ['.ts', '.js']
  },
  module: {
    rules: [
      { 
        test: /\.scss$/, 
        use: ExtractTextPlugin.extract({
          use: ['css-loader', 'postcss-loader', 'sass-loader'], // 转换 .scss 文件需要使用的 Loader
          fallback: 'style-loader',
        }),
      },
      {
        test: /\.ts$/,
        use: ['awesome-typescript-loader'],
      }
    ]
  },
  plugins: [
    new webpack.BannerPlugin('版权所有,翻版必究'),
    new HtmlWebpackPlugin({
            template: __dirname + "/app/index.html" //new 一个这个插件的实例,并传入相关的参数
        }),
    new ExtractTextPlugin({
      filename: `[name]_[contenthash:8].css` // 从 .js 文件中提取出来的 .css 文件的名称
    }),
  ],
}

在根目录下创建postcss.config.js, 来指定postcss所使用的插件。

module.exports = {
  plugins: [
    require('autoprefixer')({
      browsers: ['last 2 version'],
    }),
    require('cssnano')({
      reduceIdents: false, // http://cssnano.co/optimisations/reduceidents/
    }),
  ],
};