javascript - core-js 包很大(使用 62kB)
问题描述
我正在减少我的 js 包大小并偶然发现了 core-js。它大约需要 62kB,占整个包的 24%。
我尝试使用@babel/preset-env
,但无法进一步缩小尺寸。不确定我是否使用了“正确”的设置:
'@babel/preset-env',
{
targets: {
browsers: ['>1%'],
},
useBuiltIns: 'usage',
corejs: { version: 3, proposals: true },
},
完整的webpack.config.js
const path = require('path');
const webpack = require('webpack');
const dotenv = require('dotenv');
const copyWebpackPlugin = require('copy-webpack-plugin');
const bundleOutputDir = './dist';
/* eslint-disable import/no-extraneous-dependencies */
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
// const CompressionPlugin = require('compression-webpack-plugin');
module.exports = (env) => {
// get project ID (environment)
const projectID = process.env.PROJECT_ID;
if (!projectID || projectID === undefined) {
throw new Error('Need env variable PROJECT_ID');
}
const isDevEnvironment = !(projectID === 'production-project');
const isDevBuild = !(env && env.prod);
const analyzeBundle = env && env.analyze;
// call dotenv and it will return an Object with a parsed key
const dotEnv = isDevEnvironment ? dotenv.config({ path: './.env.development' }).parsed : dotenv.config().parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(dotEnv).reduce((prev, next) => {
const updatedPrev = prev;
updatedPrev[`process.env.${next}`] = JSON.stringify(dotEnv[next]);
return updatedPrev;
}, {});
envKeys['process.env.PROJECT_ID'] = JSON.stringify(projectID);
// need to remove quotes from env
const publicURL = 'https:/mysite.com'
const plugins = [new webpack.DefinePlugin(envKeys), new ForkTsCheckerWebpackPlugin()];
if (isDevBuild) {
// eslint-disable-next-line new-cap
plugins.push(new webpack.SourceMapDevToolPlugin(), new copyWebpackPlugin([{ from: 'dev/' }]));
} else {
// Don't need to enable compressinon plugin as Firebase Hosting automatically zips the files for us
// plugins.push(new CompressionPlugin());
}
if (analyzeBundle) {
// eslint-disable-next-line global-require
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
plugins.push(new BundleAnalyzerPlugin());
}
const babelPlugins = [
// syntax sugar found in React components
'@babel/proposal-class-properties',
'@babel/proposal-object-rest-spread',
// transpile JSX/TSX to JS
[
'@babel/plugin-transform-react-jsx',
{
// we use Preact, which has `Preact.h` instead of `React.createElement`
pragma: 'h',
pragmaFrag: 'Fragment',
},
],
[
'transform-react-remove-prop-types',
{
removeImport: !isDevBuild,
},
],
];
if (!isDevBuild) {
babelPlugins.push(['transform-remove-console', { exclude: ['error', 'warn'] }]);
}
return [
{
entry: './src/index.ts',
output: {
filename: 'widget.js',
path: path.resolve(bundleOutputDir),
publicPath: isDevBuild ? '' : publicURL,
},
devServer: {
host: '0.0.0.0', // your ip address
port: 8080,
disableHostCheck: true,
contentBase: bundleOutputDir,
open: 'google chrome',
},
plugins,
optimization: {
minimize: !isDevBuild,
nodeEnv: 'production',
mangleWasmImports: true,
removeAvailableModules: true,
usedExports: true,
sideEffects: true,
providedExports: true,
concatenateModules: true,
},
mode: isDevBuild ? 'development' : 'production',
module: {
rules: [
// packs PNG's discovered in url() into bundle
{
test: /\.(jpe?g|png|webp)$/i,
use: [
{
loader: 'responsive-loader',
options: {
// eslint-disable-next-line global-require
adapter: require('responsive-loader/sharp'),
// sizes: [160, 320, 640, 960, 1280],
name: '[path][name]-[width].[ext]',
sourceMap: isDevBuild,
},
},
],
},
{ test: /\.svg/, use: ['@svgr/webpack'] },
{
test: /\.(css)$/i,
use: [
{
loader: 'style-loader',
options: {
injectType: 'singletonStyleTag',
},
},
{
// allows import CSS as modules
loader: 'css-loader',
options: {
modules: {
// css class names format
localIdentName: '[name]-[local]-[hash:base64:5]',
},
sourceMap: isDevBuild,
},
},
],
},
{
test: /\.(scss)$/i,
use: [
{
loader: 'style-loader',
options: { injectType: 'singletonStyleTag' },
},
{
// allows import CSS as modules
loader: 'css-loader',
options: {
modules: {
// css class names format
localIdentName: '[name]-[local]-[hash:base64:5]',
},
sourceMap: isDevBuild,
},
},
{
loader: 'sass-loader',
options: {
sourceMap: isDevBuild,
},
},
],
},
// use babel-loader for TS and JS modeles,
// starting v7 Babel babel-loader can transpile TS into JS,
// so no need for ts-loader
// note, that in dev we still use tsc for type checking
{
test: /\.(js|ts|tsx|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
[
'@babel/preset-env',
{
targets: {
browsers: ['>1%'],
},
useBuiltIns: 'usage',
corejs: { version: 3, proposals: true },
},
],
[
// enable transpiling ts => js
'@babel/typescript',
// tell babel to compile JSX using into Preact
{ jsxPragma: 'h' },
],
],
plugins: babelPlugins,
},
},
],
},
],
},
resolve: {
extensions: ['*', '.js', '.ts', '.tsx'],
plugins: [new TsconfigPathsPlugin()],
alias: {
react: 'preact/compat',
'react-dom': 'preact/compat',
images: path.join(__dirname, 'images'),
sharedimages: path.resolve(__dirname, '../../packages/shared/src/resources'),
},
},
},
];
};
解决方案
看起来 @babel/preset-env 的 targets 属性不再使用,而是建议 browserlist 包含支持的浏览器列表。 https://babeljs.io/docs/en/babel-preset-env#browserslist-integration
推荐阅读
- swift - Swift Scale 自定义视图以适应其视图
- sql - 从表中查找取消和替换匹配的最佳方法
- node.js - 如何将 Numeral.js 库放入 pug 文件 Node js 中?
- c# - 如何使用时间开始移动每个对象来轮流移动每个对象?
- java - 在 ImageJ 上编译插件过滤器时出错
- angular - (Angular)如何禁用组件模板中的“链接”标签?
- node.js - 使用 .HEIC 图像类型时,Google Vision OCR 无法检测到文本或图像
- flutter - 未处理的异常:类型 '_InternalLinkedHashMap
' 不是类型 'Map 的子类型 '在飞镖 - c++ - wcout 无法在 Windows 中从 wcin 打印 wstring
- c++ - 为什么指向基类的派生类指针可以调用派生类成员函数?