在 Taro 項目中,為了減少 console 的顯示(例如 console.log、console.info 等),可以通過配置 terser-webpack-plugin 來移除生產環境中的 console 調用。
配置步驟:
修改 index.js 文件
在 mini.webpackChain 中添加 terser-webpack-plugin 配置:
const config = {projectName: 'taro-react',date: '2025-5-10',designWidth: 750,deviceRatio: {640: 2.34 / 2,750: 1,828: 1.81 / 2},sourceRoot: 'src',outputRoot: 'dist',plugins: [],defineConstants: {},copy: {patterns: [],options: {}},framework: 'react',compiler: 'webpack5',cache: {enable: false},mini: {webpackChain(chain) {// 生產環境移除 consoleif (process.env.NODE_ENV === 'production') {chain.optimization.minimize(true);chain.plugin('terser').use(require('terser-webpack-plugin'), [{terserOptions: {compress: {drop_console: true, // 移除所有 consoledrop_debugger: true // 移除 debugger}}}]);}}},h5: {publicPath: '/',staticDirectory: 'static',postcss: {autoprefixer: {enable: true,config: {}}}}
};module.exports = function (merge) {if (process.env.NODE_ENV === 'development') {return merge({}, config, require('./dev'));}return merge({}, config, require('./prod'));
};
構建生產環境代碼
使用以下命令構建生產環境代碼:
pnpm build:weapp --mode production
在 Taro 項目中,為了減少 console
的顯示(例如 console.log
、console.info
等),可以通過配置 terser-webpack-plugin
來移除生產環境中的 console
調用。
配置步驟:
-
修改 index.js 文件
在mini.webpackChain
中添加terser-webpack-plugin
配置:const config = {projectName: 'taro-react',date: '2025-5-10',designWidth: 750,deviceRatio: {640: 2.34 / 2,750: 1,828: 1.81 / 2},sourceRoot: 'src',outputRoot: 'dist',plugins: [],defineConstants: {},copy: {patterns: [],options: {}},framework: 'react',compiler: 'webpack5',cache: {enable: false},mini: {webpackChain(chain) {// 生產環境移除 consoleif (process.env.NODE_ENV === 'production') {chain.optimization.minimize(true);chain.plugin('terser').use(require('terser-webpack-plugin'), [{terserOptions: {compress: {drop_console: true, // 移除所有 consoledrop_debugger: true // 移除 debugger}}}]);}}},h5: {publicPath: '/',staticDirectory: 'static',postcss: {autoprefixer: {enable: true,config: {}}}} };module.exports = function (merge) {if (process.env.NODE_ENV === 'development') {return merge({}, config, require('./dev'));}return merge({}, config, require('./prod')); };
-
構建生產環境代碼
使用以下命令構建生產環境代碼:pnpm build:weapp --mode production
或者,如果你使用的是 npm/yarn:
npm run build:weapp --mode production # 或 yarn build:weapp --mode production
-
效果
- 生產環境中,所有
console.log
、console.info
、console.debug
等調用都會被移除。 console.warn
和console.error
不會被移除(用于調試和錯誤追蹤)。debugger
語句也會被移除。
- 生產環境中,所有
注意事項:
-
確保
terser-webpack-plugin
已安裝(Taro 默認會安裝)。 -
在開發環境中,
console
調用仍然會保留,方便調試。 -
如果需要移除所有類型的
console
,可以在terserOptions.compress
中添加更多配置,例如:compress: {drop_console: true,drop_debugger: true,pure_funcs: ['console.log', 'console.info', 'console.debug', 'console.warn', 'console.error'] }
Similar code found with 2 license types