Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

webpack 单独打包组件配置怎么写

项目名:component-package
源码目录结构:

/src
 |--index.js
 |--components
    |--demo1.js
    |--demo1.css
    |--demo2.js
    |--demo2.css

想要把src目录下的每一个组件单独打包到/dist目录,最终想要的是这样

/dist
 |--index.js
 |--style.css
 |--demo1
    |--index.js
    |--style.css
 |--demo2
    |--index.js
    |--style.css

需要实现 在引用这个组件包的项目中可以实现按需要引入效果,

//引入全部组件
import ComponentPackages from "component-package";

//单独引入某个组件
import Demo2 from "component-package/demo2";

webpack配置要怎么写?

我目前使用的是webpack v4.44.2

感谢 @redbuck ,我的解决方法:
简要写一下webpack.prod.config.js

module.exports = {
  entry: {
    index: './src/index.js',
    demo1: './src/components/demo1.js',
    demo2: './src/components/demo2.js'
  },
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name]/index.js',
    libraryTarget: 'commonjs2'
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name]/style.css"
    })
  ]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

配置多入口

{
    entry: {
        'demo1/index': 'src/components/demo1.js',
        'demo2/index': 'src/components/demo2.js',
        ...
    },
    output: {
        path: root('dist'),
        filename: '[name].js'
    }
}

可以查阅一些node的文档,编写脚本自动生成entry.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...