[英]Writing an NPM Module: Require own package as dependency
I'm creating a new NPM package. 我正在创建一个新的NPM软件包。 Within the repo, there's an
examples
directory with some javascript that gets compiled and served when running locally (or, eventually via github.io). 在存储库中,有一个
examples
目录,其中包含一些javascript,这些javascript在本地运行时(或最终通过github.io)被编译并提供服务。
The setup is similar to react-menu . 设置类似于react-menu 。 If you look inside any of the javascript files in that examples directory, you'll see that they require the package as if it had just been installed with
npm install react-menu
: 如果您查看该示例目录中的所有javascript文件,您将看到它们需要该软件包,就好像它是使用
npm install react-menu
:
import Menu, { SubMenu, Item as MenuItem } from 'rc-menu';
But, it's not listed in any of the dependencies in package.json. 但是,未在package.json的任何依赖项中列出。
I know I can require my own module with something like import myThing from '../../../index.js'
, but I'd rather not need to worry about all of the relative directories. 我知道我可以使用诸如
import myThing from '../../../index.js'
类的模块,但是我不需要担心所有相对目录。 I tried import myThing from 'my-thing'
, but it of course couldn't find the package, and failed. 我尝试
import myThing from 'my-thing'
,但是它当然找不到包,但失败了。
How is react-menu doing this? 反应菜单如何执行此操作?
Ok, I should have looked a little deeper into the webpack docs. 好的,我应该对webpack文档进行更深入的研究。
tl;dr - The solution is resolve configuration. tl; dr-解决方案是解决配置。
My directories are structured like this: 我的目录结构如下:
.
├── LICENSE.md
├── README.md
├── examples
│ ├── bundle.js
│ ├── index.html
│ ├── server.js
│ └── src
│ ├── components
│ │ ├── App.js
│ │ └── examples
│ │ └── ExampleOne.js
│ └── index.js
├── index.js
├── package-lock.json
├── package.json
├── src
│ └── index.js
├── test
├── webpack.config.js
└── webpack.examples.config.js
Just adding resolve configuration to my webpack.config.examples.js did the trick. 只需将解析配置添加到我的webpack.config.examples.js即可达到目的。 Here's the whole file, just for reference:
这是整个文件,仅供参考:
const webpack = require('webpack')
const path = require('path')
module.exports = {
entry: [
'react-hot-loader/patch',
'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
'./examples/src/index.js',
],
output: {
path: path.resolve(__dirname, 'examples'),
publicPath: '/',
filename: 'bundle.js',
sourceMapFilename: 'bundle.js.map',
},
resolve: {
alias: {
'my-package': path.resolve(__dirname, 'src'),
},
},
devtool: 'eval-source-map',
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
],
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
],
},
}
So now, when I am working anywhere within the examples app, I can just use: 所以现在,当我在示例应用程序中的任何地方工作时,我都可以使用:
import myThing from 'my-package'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.