React/Vue Webpack copy文件到build路径
目的:webpack打包时将资源文件copy到指定路径
npm install copy-webpack-plugin@5.0 -d
yarn add copy-webpack-plugin@5.0 -d
高版本的react/vue版本才能用copy-webpack-plugin@11.0.0
低版本的react/vue必须用copy-webpack-plugin@5.0
版本不匹配会出现error:compilation.getCache is not a function
并且高低版本的copy-webpack-plugin语法也不同
React
1:安装依赖copy-webpack-plugin、customize-cra、react-app-rewired
2:修改script,使用react-app-rewired命令
"build:copy": "cross-env NODE_ENV=production GENERATE_SOURCEMAP=false react-app-rewired --max-old-space-size=8192 build",
3:配置config-overrides.js
const { override, fixBabelImports } = require('customize-cra');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const copyFileConfig= ()=>(config, env)=>{
config.plugins.push(
new CopyWebpackPlugin(
[
{
from: 'assets/sample.csv',
to: 'assets/sample.csv'
}
])
);
return config;
}
module.exports = override(
copyFileConfig(),
//这里是antd的示例,与本主题无关
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
}),
);
4:打包时执行npm run build:copy即可
Vue
1:同React相似,先安装copy-webpack-plugin
2:vue.config.js -> configureWebpack加入以下代码
configureWebpack: (config) => {
const plugins = [];
plugins.push(
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, './assets'),
to: path.resolve(__dirname, './dist/assets')
}
]),
)
config.plugins = [...config.plugins, ...plugins]
}