亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使 webpack 僅針對特定構建導入 polyfill?

如何使 webpack 僅針對特定構建導入 polyfill?

叮當貓咪 2023-06-29 21:17:09
我剛剛設法讓 webpack 創建兩個單獨的構建,一個用于 es5,另一個用于 es6。請參閱下面的配置文件:const path = require("path");const common = require("./webpack.common");const merge = require("webpack-merge");const CleanWebpackPlugin = require("clean-webpack-plugin");const MiniCssExtractPlugin = require("mini-css-extract-plugin");const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");const TerserPlugin = require("terser-webpack-plugin");var HtmlWebpackPlugin = require("html-webpack-plugin");const es5Config = merge(common,{  mode: "production",  output: {    filename: "[name].[contentHash].bundle.es5.js",    path: path.resolve(__dirname, "dist")  },  optimization: {    minimizer: [      new OptimizeCssAssetsPlugin(),      new TerserPlugin(),      new HtmlWebpackPlugin({        template: "./src/template.html",        minify: {          removeAttributeQuotes: true,          collapseWhitespace: true,          removeComments: true        }      }),    ]  },  plugins: [    new MiniCssExtractPlugin({ filename: "[name].[contentHash].css" }),      new CleanWebpackPlugin(),    ],  module: {    rules: [      {        test: /\.scss$/,        use: [          MiniCssExtractPlugin.loader, //3. Extract css into files          "css-loader", //2. Turns css into commonjs          "sass-loader" //1. Turns sass into css        ]      },module.exports = [es5Config, es6Config];現在的問題是我希望 webpack 僅為 es5 構建導入 polyfill。并使用usebuilins設置為usage并不能填充任何內容。我是否可能使用錯誤,也許與 node_modules 包相關?所以我只是在主文件中導入 polyfill,例如:import "core-js/stable";import "regenerator-runtime/runtime";如何使這些導入僅添加到 es5 構建中?或者我如何包含來自 webpack 的 polyfills/imports?還有一個額外的問題,如果有人知道,我如何正確使用帶有“usage”的usebuiltins?因為到目前為止,即使我認為 polifylls 已添加到我的主文件中,例如,我仍然會在 IE11 中收到符號錯誤。
查看完整描述

1 回答

?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

我想到了。這是 webpack 配置:常見:


const path = require("path");


module.exports = {

? entry: {

? ? main: "./src/index.js",

? ? vendor: "./src/vendor.js"

? },

? module: {

? ? rules: [

? ? ? {

? ? ? ? test: /\.html$/,

? ? ? ? use: ["html-loader"]

? ? ? },

? ? ? {

? ? ? ? test: /\.(svg|png|jpg|gif)$/,

? ? ? ? use: {

? ? ? ? ? loader: "file-loader",

? ? ? ? ? options: {

? ? ? ? ? ? name: "[name].[hash].[ext]",

? ? ? ? ? ? outputPath: "imgs"

? ? ? ? ? }

? ? ? ? }

? ? ? }

? ? ]

? }

};

產品:


const path = require("path");


const common = require("./webpack.common");

const merge = require("webpack-merge");

const CleanWebpackPlugin = require("clean-webpack-plugin");

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");

const TerserPlugin = require("terser-webpack-plugin");

var HtmlWebpackPlugin = require("html-webpack-plugin");

const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");


const es5Config = merge(common,{

? mode: "production",

? output: {

? ? filename: "[name].[contentHash].bundle.es5.js",

? ? path: path.resolve(__dirname, "dist")

? },

? optimization: {

? ? runtimeChunk: 'single',

? ? splitChunks: {

? ? ? chunks: 'all',

? ? ? maxInitialRequests: Infinity,

? ? ? minSize: 0,

? ? ? cacheGroups: {

? ? ? ? vendor: {

? ? ? ? ? test: /[\\/]node_modules[\\/]/,

? ? ? ? ? name: (module) => {

? ? ? ? ? ? // get the name. E.g. node_modules/packageName/not/this/part.js

? ? ? ? ? ? // or node_modules/packageName

? ? ? ? ? ? const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

? ? ? ? ? ? // npm package names are URL-safe, but some servers don't like @ symbols

? ? ? ? ? ? return `npm.${packageName.replace('@', '')}`;

? ? ? ? ? },

? ? ? ? },

? ? ? },

? ? },

? ? minimizer: [

? ? ? new OptimizeCssAssetsPlugin(),

? ? ? new TerserPlugin(),

? ? ? new HtmlWebpackPlugin({

? ? ? ? filename: 'main.aspx',

? ? ? ? template: "./src/main.html",

? ? ? ? // minify: {

? ? ? ? //? ?removeAttributeQuotes: true,

? ? ? ? //? ?collapseWhitespace: true,

? ? ? ? //? ?removeComments: true

? ? ? ? // }

? ? ? }),

? ? ]

? },

? plugins: [

? ? new MiniCssExtractPlugin({ filename: "[name].[contentHash].css" }),

? ? new CleanWebpackPlugin(),

? ? new BundleAnalyzerPlugin(),

? ? ],


? module: {

? ? rules: [

? ? ? {

? ? ? ? test: /\.scss$/,

? ? ? ? use: [

? ? ? ? ? MiniCssExtractPlugin.loader, //3. Extract css into files

? ? ? ? ? "css-loader", //2. Turns css into commonjs

? ? ? ? ? "sass-loader" //1. Turns sass into css

? ? ? ? ]

? ? ? },

? ? ? {

? ? ? test: /\.m?js$/,

? ? ? exclude: /node_modules/,

? ? ? //exclude: /node_modules\/(?!(\@pnp)\/).*/,?

? ? ? use: {

? ? ? ? loader: 'babel-loader',

? ? ? ? options: {

? ? ? ? ? //configFile : './es5.babel.config.json',

? ? ? ? ? presets: [

? ? ? ? ? ? ['@babel/preset-env', {

? ? ? ? ? ? ? modules: false,

? ? ? ? ? ? ? useBuiltIns: false,

? ? ? ? ? ? ? targets: {

? ? ? ? ? ? ? ? browsers: [

? ? ? ? ? ? ? ? ? "IE 11"

? ? ? ? ? ? ? ? ],

? ? ? ? ? ? ? },

? ? ? ? ? ? }],

? ? ? ? ? ],

? ? ? ? },

? ? ? },

? ? }],

? },

});


const es6Config = merge(common, {

? mode: "production",

? output: {

? ? filename: "[name].[contentHash].bundle.es6.js",

? ? path: path.resolve(__dirname, "dist")

? },

? optimization: {

? ? runtimeChunk: 'single',

? ? splitChunks: {

? ? ? chunks: 'all',

? ? ? maxInitialRequests: Infinity,

? ? ? minSize: 0,

? ? ? cacheGroups: {

? ? ? ? vendor: {

? ? ? ? ? test: /[\\/]node_modules[\\/]/,

? ? ? ? ? name: (module) => {

? ? ? ? ? ? // get the name. E.g. node_modules/packageName/not/this/part.js

? ? ? ? ? ? // or node_modules/packageName

? ? ? ? ? ? const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

? ? ? ? ? ? // npm package names are URL-safe, but some servers don't like @ symbols

? ? ? ? ? ? return `npm.${packageName.replace('@', '')}`;

? ? ? ? ? },

? ? ? ? },

? ? ? },

? ? },

? ? minimizer: [

? ? ? new OptimizeCssAssetsPlugin(),

? ? ? new TerserPlugin(),

? ? ? new HtmlWebpackPlugin({

? ? ? ? filename: 'main_es6.html',

? ? ? ? template: "./src/main.html",

? ? ? ? // minify: {

? ? ? ? //? ?removeAttributeQuotes: true,

? ? ? ? //? ?collapseWhitespace: true,

? ? ? ? //? ?removeComments: true

? ? ? ? // }

? ? ? }),

? ? ]

? },

? plugins: [


? ? new MiniCssExtractPlugin({ filename: "[name].[contentHash].css" }),

? ? new CleanWebpackPlugin(),

? ? ],

? module: {

? ? rules: [

? ? ? {

? ? ? ? test: /\.scss$/,

? ? ? ? use: [

? ? ? ? ? MiniCssExtractPlugin.loader, //3. Extract css into files

? ? ? ? ? "css-loader", //2. Turns css into commonjs

? ? ? ? ? "sass-loader" //1. Turns sass into css

? ? ? ? ]

? ? ? },

? ],

? },

});

module.exports = [ es5Config, es6Config];

babel.config.json:


{

? "plugins": [

? ? [

? ? ? "@babel/plugin-transform-runtime",

? ? ? {

? ? ? ? "absoluteRuntime": true,

? ? ? ? "helpers": true,

? ? ? ? "regenerator": true,

? ? ? ? "useESModules": false

? ? ? }

? ? ]

? ]

}

因此,與 cdn polyfill 相結合,可以僅加載適用于 IE11 的 polifylls。它也有自己的構建。


這里唯一的問題是,生成的輸出將具有單獨的文件,并且 es5 構建的所有腳本中應該沒有模塊。另外對于 es6 都應該有模塊。然后我必須手動添加那些我可以輕松制作自定義模板來處理的內容。


但隨后,polyfill 的腳本被刪除,我仍然需要手動合并 html 文件。有人知道如何處理嗎?


編輯: 1 - 對于屬性,您可以使用 HtmlWebpackPlugin hooks () 或 ScriptExtHtmlWebpackPlugin 將屬性放置在標簽中。


在這里找到一些帶有鉤子的代碼:


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



class es5TagTransformerHook {

? apply (compiler) {

? ? compiler.hooks.compilation.tap('MyPlugin', (compilation) => {

??

? ? ? HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync(

? ? ? ? 'es5TagTransformerHook', stacktraces

? ? ? ? async (data, cb) => {

? ? ? ? ? // Manipulate the content

? ? ? ? ? // data.html += 'The Magic Footer'

? ? ? ? ? // Tell webpack to move on

? ? ? ? ? data.bodyTags.forEach(t=>t.tagName === 'script'?t.attributes.nomodule = true:null)


? ? ? ? ? cb(null, data)

? ? ? ? }

? ? ? )

? ? ??

? ? })

? }

}


module.exports = es5TagTransformerHook

查看完整回答
反對 回復 2023-06-29
  • 1 回答
  • 0 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號