返回

webpack4新手小贴士:生成html、添加css3前缀、babel配置等操作

前端

在webpack4中,我们可以通过配置来生成html、添加css3前缀和配置babel。这些配置可以帮助我们更轻松地开发前端项目。

html生成

使用webpack4生成html,需要安装html-webpack-plugin插件。

npm install --save-dev html-webpack-plugin

然后,在webpack的配置文件中配置html-webpack-plugin插件。

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

module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: './index.html'
    })
  ]
};

这样,webpack在构建项目时,就会自动生成index.html文件。

css3前缀添加

使用webpack4添加css3前缀,需要安装postcss-loader和autoprefixer插件。

npm install --save-dev postcss-loader autoprefixer

然后,在webpack的配置文件中配置postcss-loader和autoprefixer插件。

const autoprefixer = require('autoprefixer');

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1
            }
          },
          {
            loader: 'postcss-loader',
            options: {
              plugins: [autoprefixer]
            }
          }
        ]
      }
    ]
  }
};

这样,webpack在构建项目时,就会自动在css文件中添加css3前缀。

babel配置

使用webpack4配置babel,需要安装babel-loader插件。

npm install --save-dev babel-loader @babel/core @babel/preset-env

然后,在webpack的配置文件中配置babel-loader插件。

const babel = require('@babel/core');

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: babel.loadOptions({
            presets: ['@babel/preset-env']
          })
        }
      }
    ]
  }
};

这样,webpack在构建项目时,就会自动使用babel将es6代码转换成es5代码。

以上是webpack4中生成html、添加css3前缀和配置babel的操作方法。希望这些内容对您有所帮助。