【发布时间】:2016-11-02 11:32:58
【问题描述】:
我正在为 React 创建一个小型组件库。像var Components = require('components') 这样可能需要的东西。这将有单独的组件,就像react-bootstrap 一样。我正在尝试使用带有 babel 的 webpack 将其编译为 index.js 文件。编译进行得很顺利。我将此发布到我的本地 npm 注册表并将其安装在我的其他项目之一中。当我需要它时 - require('components') - 需要返回一个空对象。下面是我的文件夹结构
root
|- components
| |- ImageEditor.js
|
|- lib
| |- index.compiled.js (file compiled by webpack)
|
|- index.js (requires ./components/ImageEditor.js, entry point for webpack)
|- webpack.config.js
ImageEditor.js
import React from 'react';
import ReactDOM from 'react-dom';
import Canvas from './utils/canvas';
import '../stylesheets/imageeditor.scss';
class ImageManipulation extends React.Component {
static propTypes = {};
state = {
height: 200,
width: 200,
scale: 1.25
};
static defaultProps = {
color: [213, 214, 217, 0.6],
image: ""
};
...
render() {
return (
<div className="_react-image-manipulation">
<div className="_cover-box">
{ this.loadComponent() }
</div>
</div>
);
}
}
export default ImageManipulation;
index.js
import ImageEditor from './components/ImageEditor';
export default {
ImageEditor
};
webpack.config.js
var path = require('path');
var NODE_ENV = process.env.NODE_ENV || 'development';
var WebpackNotifierPlugin = require('webpack-notifier');
var UglifyJSPlugin = require("webpack/lib/optimize/UglifyJsPlugin");
var CleanWebpackPlugin = require("clean-webpack-plugin");
var commonPlugins = [
new WebpackNotifierPlugin({
title: 'Contour Components'
})
];
function getPlugins() {
if (NODE_ENV == 'prod') {
commonPlugins.push(new CleanWebpackPlugin(['lib/*']));
commonPlugins.push(new UglifyJSPlugin({
compress: {
warnings: false
}
}));
}
return commonPlugins;
}
module.exports = {
devtool: 'sourcemap',
entry: {
index: './index.js'
},
output: {
path: path.join(__dirname, 'public'),
filename: '[name].compiled.js'
},
plugins: getPlugins(),
module: {
loaders: [{
test: /\.js$/,
loader: 'babel',
query: {
cacheDirectory: true,
presets: ['es2015', 'stage-0', 'react'],
plugins: ['add-module-exports', "transform-class-properties"]
},
exclude: /node_modules/
}, {
test: /\.json$/,
loader: 'json-loader'
}, {
test: /\.png$/,
loader: "url-loader?limit=100000&mimetype=image/png"
}, {
test: /(\.scss|\.css)$/,
include: /components/,
loader: 'style!css!sass'
}]
},
resolve: {
extensions: ['', '.scss', '.js', '.json', '.png'],
modulesDirectories: [
'node_modules',
'components'
]
}
};
知道我在这里做错了什么吗?
【问题讨论】:
-
你有 package.json 吗?在本地注册表中安装是指
npm link还是cp my-module node_modules/之类的东西? -
我们已经设置了一个本地 npm 注册表。我已发布到该注册表。在我的另一个项目中,我已将此添加为依赖项。
npm install从该注册表中获取已发布的模块并安装它。我不认为这与此有任何关系。因为,我创建了另一个js文件,它需要生成的文件index.compiled.js,并将组件渲染成index.html。然后我将此文件托管在本地节点服务器中。即使这样也没有用。它因同样的错误而失败。 -
package.json 是否明确指定了您的主文件?如果您在其他项目中查看
node_modules/components,文件是否符合您的预期? -
是的,所有文件都符合我的预期。还明确提到了主文件。但即使没有发布,它也不能在简单的节点服务器中本地工作
标签: javascript reactjs ecmascript-6 webpack babeljs