一、背景
在开发一个 NPM 包时,常常需要用 rollup 打包,用 webpack 开发调试,处理环境变量的时候就需要兼容两种工具的打包方式。
二、rollup - rollup-plugin-replace
配置
// rollup.config.js
import babel from 'rollup-plugin-babel';
import replace from 'rollup-plugin-replace';
export default {
input: 'src/index.m.js',
output: {
file: 'lib/index.cjs.js',
format: 'cjs'
},
plugins: [
babel(),
replace({
ENV: JSON.stringify(process.env.NODE_ENV || 'development')
})
]
};
源代码
// load
if (ENV === 'development') {
console.log('开发模式!')
}
NODE_ENV=development npx rollup -c rollup.config.js 编译后
{
console.log('开发模式!');
}
三、webpack - webpack.DefinePlugin
配置
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: {
test: './src/test.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
filename: path.resolve(__dirname, 'dist/index.html'),
template: path.resolve(__dirname, 'src/test.html'),
inject: true,
chunksSortMode: 'dependency'
}),
new CleanWebpackPlugin(['dist']),
new webpack.DefinePlugin({
ENV: JSON.stringify(process.env.NODE_ENV || 'development')
})
]
};